12

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?

genesis
  • 50,477
  • 20
  • 96
  • 125
  • Have you seen this question - http://stackoverflow.com/questions/70272/single-form-hide-on-startup – ipr101 Aug 09 '11 at 22:09

3 Answers3

19

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.

Daniel Walker
  • 760
  • 6
  • 11
  • and how can I trigger it when form is being visible? – genesis Aug 09 '11 at 22:07
  • Maybe put that code in an event that fires later in the sequence? Or hide the form in the code that instantiates the form? – Code Magician Aug 09 '11 at 22:09
  • 1
    @magicmike That's what I was thinking. After instantiating the form, he could just wait to call ShowDialog() until later. Unless he's depending on some code in the Form's constructor to run... – Daniel Walker Aug 09 '11 at 22:11
  • For your question: I'm going to create toolTip icon application. I have no idea how to do it without windows forms. – genesis Aug 09 '11 at 22:12
6

Because you're calling Hide() before the form is shown.

http://msdn.microsoft.com/en-us/library/86faxx0d.aspx

Code Magician
  • 23,217
  • 7
  • 60
  • 77
4

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536