简体   繁体   中英

How do I make the close button of a Windows Form not close the form but make it invisible?

This form has a NotifyIcon object. When the user clicks on the Close button, I want the form not to close but to become invisible. And then, if the user wants to see the form again, he can double click on the icon in the systray. If the user wants to close the form, he can right click on the icon and select "close".

Can someone tell me how to make the close button not close the form but make it invisible?

(or if someone can think of a better way to achieve the same objective by all means)

First, you want to handle your Main form's .FormClosing event (or by overriding the OnFormClosing method). Cancel that by setting e.Cancel to true.

Then, you use a NotifyIcon to add an icon to the system tray.

Finally, hide the form by calling .Hide() .

protected override void OnFormClosing(FormClosingEventArgs e) {
    if (IActuallyWantToCloseFlag)
        return;

    var ni = new NotifyIcon(this.components)
    {
        Icon = someIcon,
        Text = "My text",
        Visible = true
    };
    ni.DoubleClick += (sender, args) => { this.Show(); };

    this.Hide();
    e.Cancel = true;
}

This should get you started. You probably want to make ni a member variable, so that you can continue to hide/show the icon as you show/hide your form.

You could try making it a tray icon app. There's a good tutorial here for that: http://www.developer.com/net/net/article.php/3336751/C-Tip-Placing-Your-C-Application-in-the-System-Tray.htm

实现所需内容的最简单方法是订阅FormClosing事件并通过包含此类代码设置可见的false:

FormClosing += (sender, args) => { args.Cancel = true; Visible = false; };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM