C# close to tray (like msn messenger)
Asked Answered
I

3

5

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?

Impede answered 28/7, 2010 at 3:27 Comment(1)
Application.exit() won't work because that still triggers the form closing event. I think, as some people have mentioned, I will need to use a flag to signal where the request is coming from (tray menu vs x button)Impede
F
3

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

Fungi answered 28/7, 2010 at 3:35 Comment(0)
C
0

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.

Charnel answered 28/7, 2010 at 3:33 Comment(0)
A
0

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

Aerodontia answered 28/7, 2010 at 3:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.