why isn't this.Hide() working in Form1_load event?

后端 未结 3 489
轻奢々
轻奢々 2020-12-01 23:54

I have actually one classic Windows form and one button. I have this code

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Hide();
         


        
相关标签:
3条回答
  • 2020-12-02 00:27

    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.

    0 讨论(0)
  • 2020-12-02 00:34

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

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

    0 讨论(0)
  • 2020-12-02 00:51

    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.

    0 讨论(0)
提交回复
热议问题