How can I detect the click event of the close (X) button at the top right corner of the control box of a form/window? Please note, I don't want to know about CloseReason, FormClosing, FormClosed or stuffs like these, unless they are inevitable. I exactly want to detect if the user clicked the X button of the form. Thanks.
Detecting X button click of a window in winforms.
Collapse
X
-
As far as I know, there is no other way to detect this. Simply make sure to have a flag to be used to detect any other control set to close the form, and then check for e.CloseReason == CloseReason.Use rClosing in the FromClosing event to make sure that the window isn't being closed by the parent or the OS. -
The only other thing I might suggest is dig through the WinAPI functions and see if you can figure out where exactly that close button is. Then you can globally check to see if the mouse button is clicked. If so, and if the form is in focus, is the cursor within the bounds of the close button.
This will likely be tricky. It would be much easier to rely on the form closing event (or what have you), so perhaps you could describe why you need to know about the X button being clicked and what you want to accomplish? Maybe we can then help you accomplish that.Comment
-
Here's a sample you can try and see if it does what you need. It's not 100% tested but it should at least get you going down the right path. I know of no other way than using the Closing event to check for something like that
Code:public const int SC_CLOSE = 61536; public const int WM_SYSCOMMAND = 274; public bool close = false; protected override void WndProc(ref Message msg) { if (msg.Msg == WM_SYSCOMMAND && msg.WParam.ToInt32() == SC_CLOSE) { this.close = true; } base.WndProc (ref msg); } private Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (this.close) { // X button clicked.. } }Last edited by PsychoCoder; Mar 2 '12, 01:45 AM.Comment
-
Using a KeyDown event and a KeyUp event you could check for the user pressing alt (you get a KeyDown when the user presses it, and a KeyUp when he/she stops); use this to exclude alt-F4. The condition you need in the KeyDown and KeyUp events is:
You need to set the form's KeyPreview property to true.Code:if (e.KeyCode == Keys.Alt)
Comment
Comment