Search code examples
winforms.net-2.0wndprocwindows-messages

Capturing WndProc message of a certain button click


I have a cancel button on my form. I want to determine inside the WndProc method that this Cancel button is clicked and write some code for it. This is absolutely necessary because otherwise I'm not able to cancel all other control validation events that are yet to be performed.

Please help.

.NET - 2.0, WinForms


Solution

  • This is how you could parse the WndProc message for a left-click on a child control:

    protected override void WndProc(ref Message m)
    {
        // http://msdn.microsoft.com/en-us/library/windows/desktop/hh454920(v=vs.85).aspx
        // 0x210 is WM_PARENTNOTIFY
        // 513 is WM_LBUTTONCLICK
        if (m.Msg == 0x210 && m.WParam.ToInt32() == 513) 
        {
            var x = (int)(m.LParam.ToInt32() & 0xFFFF);
            var y = (int)(m.LParam.ToInt32() >> 16);
    
            var childControl = this.GetChildAtPoint(new Point(x, y));
            if (childControl == cancelButton)
            {
                // ...
            }
        }
        base.WndProc(ref m);
    }
    

    BTW: this is 32-bit code.