How to capture event of clicking a window's x button (top right corner)

fylix0000
fylix0000 used Ask the Experts™
on
Hi,

I am trying to catch the event when somebody tries to close out a window by clicking the red x button on top right corner of that window.

I want to do this in C# for the application window form and not the web window.  I have tried to look over MSDN but I could not find anything on it, maybe I might have misread it?

Please note I am not trying to catch the window.Close() event which what clicking x will eventually do but rather catching the actual event when that button is clicked.

Thank you,
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Try handling FormClosing Event.

High School Computer Science, Computer Applications, Digital Design, and Mathematics Teacher
Top Expert 2009
Commented:
Add this to your Form:

        protected override void WndProc(ref Message m)
        {
            const int WM_SYSCOMMAND = 0x0112;
            const int SC_CLOSE = 0xF060;

            if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
            {
                // ...you get in here when the USER has clicked the red 'X' in the top right of the Form...

                // (toggle a class level boolean flag if you need to use this information elsewhere...like the FormClosing event)
            }

            base.WndProc(ref m);
        }

Author

Commented:
Thank you,

worked like a charm for what I am trying to do.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial