"x" To minimize WinForm, ContextMenu to close WinForm?

I have a WinForm that I want to minimize when I click the "x" in the upper right corner. For this, I:

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

This is good and good, but now I have a context menu in which it is possible to close WinForm, but because of the above code, it simply minimizes the window.

How can I make everything work the way I want?

+7
c # winforms
source share
4 answers

The click event handler has the bool flag set, which is used in the FormClosing event FormClosing .

Reset code example:

 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; } } } 
+10
source share

You need to set the flag by clicking the Close menu.

Then you can check the flag in FormClosing and do nothing.

0
source share

Both X and the system context menu send the same Windows message; do not think that you can easily split the action. This is also Alt + F4 post.

I would also say that I would not like this non-standard behavior, if I get into X, I want it to be closed, and not minimized, then that for button 2 on the left.

Perhaps the best approach to looking and feeling wrong is to not display the X button by default - disable the default function, and instead draw your own event. This can go bad in the system context menu, so you no longer have the close option.

0
source share

You can check the sender to see if it is a context and is acting accordingly?

0
source share

All Articles