Search code examples
c#.netwinformswndprocwindows-messages

Capture Window Messages (WM) in WinForms Designer using WndProc


I am writing a custom control in .NET Windows Forms. Consider the following code:

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);
    switch(m.Msg)
    {
        case WM_LBUTTONDOWN: // Yes, it's defined correctly.
            MessageBox.Show("Left Button Down");
            break;
    }
}

It works when running, but I need it to work in the designer. How can I achieve this?

NOTE:

I guess someone might say that "You can't detect clicks in the designer because the design surface captures them and processes them as part of the design process"

...Take for example the TabControl. When you add a new tab, you can click to navigate through the tabs, and then click the tab's designable area to begin designing the tab page's content. How does that work?


Solution

  • Well, designer eats some of the messages. If you want all messages to be sent to the Control, you need to create a custom control designer and send them to the control.

    Refer ControlDesigner.WndProc

    public class CustomDesigner : ControlDesigner
    {
        protected override void WndProc(ref Message m)
        {
            DefWndProc(ref m);//Passes message to the control.
        }
    }
    

    Then apply the DesignerAttribute to your custom control.

    [Designer(typeof(CustomDesigner))]
    public partial class MyUserControl : UserControl
    {
        public MyUserControl()
        {
            InitializeComponent();
        }
    
        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            const int WM_LBUTTONDOWN = 0x0201;
            switch (m.Msg)
            {
                case WM_LBUTTONDOWN: // Yes, it's defined correctly.
                    MessageBox.Show("Left Button Down");
                    break;
            }
        }
    }
    

    Drag your control to the Form, click on it. Now you should see the message box in designer also :)