Capture Window Messages (WM) in WinForms Designer using WndProc

半世苍凉 提交于 2019-12-23 03:49:20

问题


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?


回答1:


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 :)



来源:https://stackoverflow.com/questions/30468574/capture-window-messages-wm-in-winforms-designer-using-wndproc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!