Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"x" To Minimize WinForm, ContextMenu To Close WinForm?

Tags:

c#

winforms

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?

like image 400
sooprise Avatar asked Jun 15 '10 21:06

sooprise


1 Answers

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;
        }
    }

}
like image 59
Fredrik Mörk Avatar answered Oct 28 '22 14:10

Fredrik Mörk