this.Visible is not working in Windows Forms

2019-01-03 16:53发布

I have a problem. I need to hide my window at window load. But

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Visible = false;
    }

is not working. And property Visible remains true. Am I missing something?

9条回答
Anthone
2楼-- · 2019-01-03 17:37

Put your call in Windows event loop like this:

WindowsFormsSynchronizationContext.Current.Post((obj) => this.Hide(), null);

So Hide() will be invoked later, hence fix your problem.

查看更多
你好瞎i
3楼-- · 2019-01-03 17:39

Use this.Opacity = 0;

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-03 17:44

Call Hide() in the Shown event, Hide() only sets Visible to false, and before the form is being shown the Visible property is already false...

查看更多
虎瘦雄心在
5楼-- · 2019-01-03 17:45

I think it is not good idea to set visibility from form's Load event. Instead, I would do it by add a public method:

public void LoadForm(...)
{
   // do the all the initializations
}

and call the method to load the form. The form should be not visible unless you explicitly show it:

MyForm instance = new MyForm();
instance.LoadForm(...);
// instance.Show(); or ShowDialog() for dialog form not sure exactly the syntax.
查看更多
Melony?
6楼-- · 2019-01-03 17:49
this.Opacity = 0;
this.ShowInTaskbar = false;
查看更多
淡お忘
7楼-- · 2019-01-03 17:50

Yes, the Visible property is a big deal in Windows Forms, that's what actually gets the handle created and causes OnLoad() to run. In other words, the window doesn't exist until it gets visible. And it will ignore attempts to undo this.

It is pretty common to want to still create the handle but not make the window visible if you use a NotifyIcon. You can achieve this by overriding SetVisibleCore:

    protected override void SetVisibleCore(bool value) {
        if (!this.IsHandleCreated) {
            value = false;
            CreateHandle();
        }
        base.SetVisibleCore(value);
    }

Beware that OnLoad still won't run until the window actually gets visible so move code into the constructor if necessary. Just call Show() in the NotifyIcon's context menu event handler to make the window visible.

查看更多
登录 后发表回答