tags:

views:

53

answers:

4

Hi SO,

I have a WinForm that I want to minimize when the "x" in the top right corner is clicked. To accomplish this, I have:

    private void Form_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
        WindowState = FormWindowState.Minimized;
    }

That's all well and good, but now I have a context menu that has the option to close the WinForm, but because of the code above, it simply minimizes the window.

How can I get everything to work the way I want it to?

+5  A: 

Have the click event handler set a bool flag that is used in the FormClosing event handler.

Stripped down code sample:

public class YourForm : Form
{    
    private bool _reallyClose;

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

    private void Form_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (!_reallyClose)
        {
            e.Cancel = true;
            WindowState = FormWindowState.Minimized;
        }
    }

}
Fredrik Mörk
Thanks for the code example! :)
Soo
Worked perfectly!
Soo
A: 

You need to set a flag when clicking the Close menu.

You can then check for the flag in FormClosing and do nothing.

SLaks
A: 

Both the X and the system context menu send the same Windows Message, don't think you can seperate the action easily. It's also the Alt+F4 message.

I'd also say I wouldn't like this non standard behavior, if I hit the X I want it closed, not minimised, thats what the button 2 to the left is for.

Perhaps the best approach to have the look and feel you want is not to display the default X button - turn off the default feature, but instead draw your own with your own event. This may mess with the system context menu so that you no longer have a close option there either.

Greg Domjan
I forgot to mention this is for a tray application. So pressing "x" removes the window from sight, but the application is still running in the tray.
Soo
is the context menu you refer to the one from the tray icon or the system one from the title bar of the window you wish to hide, or some other context menu?
Greg Domjan
A: 

Can you check the sender to see if it is a contextmenuitem and act appropriately?

reuscam