why isn't this.Hide() working in Form1_load event?
I have actually one classic Windows form and one button. I have this code
private void Form1_Load(object sender, EventArgs e)
{
this.Hide();
this.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
this.Hide();
}
I would like to know why isn't form hidden just after it is being loaded but works when I click on that button? Can somebody explain it?
The Load event fires before the form is actually visible. Try using the Form.Shown event. This will fire when the form is actually painted on-screen.
Because you're calling Hide() before the form is shown.
http://msdn.microsoft.com/en-us/library/86faxx0d.aspx
The Visible property is a very big deal for forms. Ties into the traditional .NET programming model of only ever allocating resources at the last possible moment. Lazy.
The Load event is fired right after the native Windows window is created, just before it becomes visible to the user. It is the act of setting Visible = true that triggers this chain of events. Or more typically, calling the Show() method. Exact same thing. Not until then does the native window matter.
That does however have a side effect, you cannot set Visible to false (or call Hide, same thing) while it is in the process of setting Visible = true. Which is why your code doesn't work.
It is possible to get what you want, not terribly unusual if you have a NotifyIcon and don't want to make the window visible until the user clicks the icon. The NI can't work until the form is created. Make that look like this:
protected override void SetVisibleCore(bool value) {
if (!IsHandleCreated && value) {
base.CreateHandle();
value = false;
}
base.SetVisibleCore(value);
}
Which lets you call Show() for the first time but not actually get a visible window. It behaves normal after this. Beware that the Load event won't run, it is best not to use it.