Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

c# - this.Visible is not working in Windows Forms

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...