Window not activated when the application is run from Task Scheduler

╄→尐↘猪︶ㄣ 提交于 2021-01-29 04:52:54

问题


In my appplication I am trying to focus a textbox so I can type straight away after the Form is loaded.
When the Form is shown, I can see is the cursor blinking in the TextBox but if I type something nothing happens.
I need to click the Window to start entering text in the TextBox. If I run my application normally from Visual Studio, it will work perfectly, but if my application is run using the Task Scheduler, then this happens.
Do you have any advice?

Below is my code:

this.TopMost = true;
textbox.Focus();

I also tried textbox.Select(); but it doesn't work anyway.


回答1:


The problem: when the application is run by a Task Scheduler Action, the main Window is shown non-active and the System notifies the User flashing the application's icon in the Task Bar. This is by design.

A simple workaround is to set the startup Window's WindowState = FormWindowState.Minimized in the Form Designer, then set it back to FormWindowState.Normal after the Window has completed loading its content and it's ready to be presented, raising the Shown event.

Setting FormWindowState.Normal causes a call to ShowWindow with nCmdShow set to SW_SHOWNORMAL:

Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.

The Window is now shown as usual, active and ready to receive input.
Also, the code sets explicitly the Control that should receive the input, using the ActiveControl property.

I suggested to make the Shown handler async and add a small delay before re-setting the WindowState property, to prevent the Task Bar icon from getting stuck in a blinking state.

If the Window needs to be repositioned or resized, this needs to be done after the WindowState has been reset, since the Window is in a minimized state before that and won't cache position an size values.
The Form's StartPosition should be set to FormStartPosition.Manual

private async void MainForm_Shown(object sender, EventArgs e)
{
    await Task.Delay(500);
    this.WindowState = FormWindowState.Normal;
    this.ActiveControl = [A Control to activate];
}


来源:https://stackoverflow.com/questions/60374401/window-not-activated-when-the-application-is-run-from-task-scheduler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!