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];
}