我正在用.NET Windows窗体编写自定义控件.考虑以下代码:
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?
注意:
我猜可能有人会说:"您无法在设计器中检测到点击,因为设计表面会捕获这些点击并将其作为设计过程的一部分进行处理"
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"
...例如以TabControl为例.添加新选项卡时,可以单击以浏览选项卡,然后单击选项卡的可设计区域以开始设计选项卡页面的内容.怎么运作的?
...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?
推荐答案设计人员会吃一些消息.如果要将所有消息发送到Control,则需要创建一个自定义控件设计器并将其发送到控件.
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.
引用 ControlDesigner.WndProc
public class CustomDesigner : ControlDesigner { protected override void WndProc(ref Message m) { DefWndProc(ref m);//Passes message to the control. } }然后将DesignerAttribute应用于自定义控件.
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; } } }将控件拖到Form,单击它.现在您还应该在设计器中看到消息框:)
Drag your control to the Form, click on it. Now you should see the message box in designer also :)
更多推荐
使用WndProc在WinForms Designer中捕获窗口消息(WM)
发布评论