简体   繁体   English

将表格最小化到托盘时单击鼠标右键

[英]Right click when form is minimized to tray

I overridden the FormClosing event to minimize to system tray when clicked. 单击时,我重写了FormClosing事件以最小化到系统托盘。 Here is my code: 这是我的代码:

    private void OnFormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.UserClosing)
        {
            e.Cancel = true;
            this.Hide();

            notifyIcon.BalloonTipText = "Server minimized.";
            notifyIcon.ShowBalloonTip(3000);
        }
        else
        {
            this.Close();
        }
    }

And I also set the notifyIcon's DoubleClick event as well, here is the code: 我还设置了notifyIcon的DoubleClick事件,这是代码:

    private void showWindow(object sender, EventArgs e)
    {
        Show();
        WindowState = FormWindowState.Normal;
    }

I have two questions regarding this: 我对此有两个问题:

1) Now, when the upper-right "X" button is clicked, the application is minimized to the tray, but I can't close it (makes sense...). 1)现在,当单击右上角的“ X”按钮时,该应用程序将最小化到托盘中,但是我无法将其关闭(有意义……)。 I wish to click right click on the icon in the system tray, and that it will open a menu with, let's say, these options: Restore, Maximize and Exit. 我希望右键单击系统任务栏中的图标,它将打开一个菜单,这些菜单可以说是以下选项:Restore(还原),Maximize(最大化)和Exit(退出)。

2) (This is may be related to me exiting the program with shift+f5 since I can't, for now, close my application because of the changes I mentioned). 2)(这可能与我用shift + f5退出程序有关,因为由于我提到的更改,目前暂时无法关闭我的应用程序)。 When the application quits, after I minimzed it to the tray, the icon is left in the tray, until I pass over it with my mouse. 当应用程序退出时,将其最小化到任务栏中后,该图标将保留在任务栏中,直到我用鼠标越过它为止。 How can I fix it? 我该如何解决?

Just add a variable that indicates that the close was requested by the context menu. 只需添加一个变量,指示上下文菜单请求关闭即可。 Say: 说:

    private bool CloseRequested;

    private void exitToolStripMenuItem_Click(object sender, EventArgs e) {
        CloseRequested = true;
        this.Close();
    }

    protected override void OnFormClosing(FormClosingEventArgs e) {
        base.OnFormClosing(e);
        if (e.CloseReason == CloseReason.UserClosing && !CloseRequested) {
            e.Cancel = true;
            this.Hide();
        }
    }

Be sure to not call Close() in the FormClosing event handler, that can cause trouble when the Application class iterates the OpenForms collection. 确保不要在FormClosing事件处理程序中调用Close(),这会在Application类迭代OpenForms集合时引起麻烦。 The possible reason that you are left with the ghost icon. 您留下鬼图标的可能原因。 No need to help. 无需帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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