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
you can use this line of code. It wont hide it, but it will be minimized:
this.WindowState = FormWindowState.Minimized;
in addition, if you don't want it showing on the task bar either, you can add this line:
this.ShowInTaskbar = false;
But why do you create the form if you don't want it to be visible in the first place?
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;
If you would rather use this.Hide or this.Show you can do this
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
this.Hide();
}
Just override the OnVisibleChanged method and change the visibility of the form in there, something like this:
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
this.Visible = false;
}
And that's it! Simple and clean.
You can start a form hidden using Form.Hide()
:
Form2 form = new Form2();
//Start Form2 hidden
form.Hide();
//Close Form2
form.Close();
Try setting the visible property of the form to false before it is loaded in the main entry point of your application.
Form1 obj = new Form1();
obj.visible = false;
Application.Run(obj);
Or try setting the co-ordinates of the form to higher location like 9000, 9000.