Detecting X button click of a window in winforms

2019-07-16 11:18发布

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.

2条回答
可以哭但决不认输i
2楼-- · 2019-07-16 11:47

If you really have a good reason not to use FormClosing, CloseReason, ..., you can override the window procedure and write something like this:

    protected override void WndProc(ref Message m)
    {
        const int WM_NCLBUTTONDOWN = 0x00A1;
        const int HTCLOSE = 20;

        if (m.Msg == WM_NCLBUTTONDOWN)
        {
            switch ((int)m.WParam)
            {
                case HTCLOSE:
                    Trace.WriteLine("Close Button clicked");
                    break;
            }
        }

        base.WndProc(ref m);
    }

The details can be found here and here.

查看更多
孤傲高冷的网名
3楼-- · 2019-07-16 12:09

I know this is old thread, but here is a solution.

To get WM_NCLBUTTONUP work, don't call to base WndProc when you get WM_NCLBUTTONDOWN message :

    protected override void WndProc(ref Message m)
    {
        const int WM_NCLBUTTONDOWN = 0x00A1;
        const int WM_NCLBUTTONUP = 0x00A2;
        const int HTCLOSE = 20;

        if (m.Msg == WM_NCLBUTTONDOWN)
        {
            switch ((int)m.WParam)
            {
                case HTCLOSE:
                    // WndProc Form implementation is buggy :
                    // to receive WM_NCLBUTTONUP message,
                    // don't call WndProc.
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }
        else
        {
            if (m.Msg == WM_NCLBUTTONUP)
            {
                switch ((int)m.WParam)
                {
                    case HTCLOSE:
                        Trace.WriteLine("Close Button clicked");
                        Close();    // Optional
                        break;
                }
            }

            base.WndProc(ref m);
        }
    }
查看更多
登录 后发表回答