I wanted to hide the main window of my app on startup, so I put this in the constructor:
this.Hide();
This doesn\'t hide my form though. It
I tried to do this by setting Visible to false or hiding in the constructor and in the OnLoad event.
Neither of these had any effect, as the form is set to Visible after the form is created and after the OnLoad event is fired, in SetVisibleCore.
Setting the form to hidden in the Shown event works, but the form flickers on the screen for a moment.
You can also override the SetVisibleCore and set the value to false, but then OnLoad isn't fired and some of the other events are messed up, such as form closing.
The best solution in my opinion is to set the form to minimised and not shown in the taskbar before calling Application.Run().
So instead of:
Application.Run(new MainForm());
do:
MainForm form = new MainForm();
form.WindowState = FormWindowState.Minimized;
form.ShowInTaskbar = false;
Application.Run(form);
Then the application will run with all the proper events fired (even OnShown) and the form will not be displayed.
If you want to be able to hide / show the form like normal after that, then you need to set the WindowState and ShowInTaskbar back to Normal and true.
In the Shown event, you can set ShownInTaskbar back to true and then properly hide the form.
this.Shown += new System.EventHandler(this.MainFormShown);
...
void MainFormShown(object sender, EventArgs e)
{
this.ShowInTaskbar = true;
this.Visible = false;
}
Settings the WindowState back to Normal whilst the form is hidden has no effect, so you will need to do it after you show the form again, otherwise the icon will be in the taskbar but the form will be minimised.
this.Show();
this.WindowState = FormWindowState.Normal;