如何使Windows窗体的关闭按钮不会关闭形式,但使不可见?窗体、按钮、形式、Windows

2023-09-05 00:48:59 作者:冷心为帝

这种形式有一个NotifyIcon的对象。当用户点击关闭按钮,我希望表单不收,但要成为无形。然后,如果用户想再次看到形式,他可以双击系统托盘上的图标。如果用户想要关闭的形式,他可以用鼠标右键单击该图标,选择关闭。

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)

推荐答案

首先,你要处理你的主窗体的的 .FormClosing 事件(或通过重写的 OnFormClosing 法)。取消通过设置 e.Cancel 为true。

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.

然后,您可以使用 NotifyIcon的 以一个图标添加到系统托盘中。

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

最后,隐藏调用 .Hide() 。

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;
}

这应该让你开始。你可能想使 NI 一个成员变量,这样就可以继续隐藏/显示图标,当你显示/隐藏表单。

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.

 
精彩推荐
图片推荐