C# close to tray (like msn messenger)

霸气de小男生 提交于 2019-12-07 06:04:35

问题


I have a c# .net app. So I created a notifyIcon that sits in the tray. What I want to do is when the user hits the "x" button on the form, I want it to close to the tray. They should only be able to exit program by using the context menu in the tray icon.

So what I did was, on the form close event, I check whether the form is visible. If its visible, i set it to invisible and set showInTaskbar to false (simulating minimize to tray) If the form is invisible already, then they are probably closing it from the tray, so I will exit the program in that case.

However, the problem I have is that if the window is visible, but they right click on the context menu of the tray icon and hit exit, I need to exit the program and not minimize.

How do I solve this problem?


回答1:


try this:

bool _closingFromMenu;

void NOTIFYICON_EXIT_MENU_HANDLER(object sender, EventArgs e)
{
    _closingFromMenu = true;
    Close();
}

//form closing handler
FormClosing +=(a,b) =>{
    if(_closingFromMenu){
        Close();
    }
    else{
        e.Cancel = true;
        //do minimize stuff;
    }
}

or if you have only one form you can call Application.Exit(); in context menu item handler




回答2:


You probably want to track the state of the application based on the actions of the user as that's not necessarily reflected in the state of the window. So when the user selects Exit from the menu you need to set a flag to indicate that you're really exiting, not just hiding the window.




回答3:


Just make your Context Menu close event call Application.Exit()



来源:https://stackoverflow.com/questions/3349709/c-sharp-close-to-tray-like-msn-messenger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!