views:

151

answers:

3

Hi guys,

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?

A: 

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.

Andrew Kennan
+1  A: 

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

TheVillageIdiot
A: 

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

bashmohandes