【问题标题】:How can I intercept wndproc of parent form in usercontrol如何在用户控件中拦截父表单的 wndproc
【发布时间】:2018-02-27 08:42:08
【问题描述】:

有没有在用户控件中接收父窗体的wndproc的方法?

我正在制作标题栏用户控件,我想接​​收有关窗体大小调整的 Windows 消息。

(此表单为 formborderstyle=none。)

【问题讨论】:

    标签: c# wndproc


    【解决方案1】:

    由于WndProc 函数不会拦截所有Windows 消息,因此我习惯于创建MessageFilter,因为它会过滤每条Windows 消息。所以首先你创建一个新的类来实现接口IMessageFilter

    class MessageFilter : IMessageFilter
    {
        public static IntPtr MyHandle { get; set; }
    
        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == /*windows code for resizing*/ && m.HWnd == MyHandle)
            {
                //do what you desire
                return true;
            }
            else
                return false;
        }
    }
    

    因此,您过滤所有消息并等待消息包含调整大小的代码并且该代码针对您的特定窗口。在 Windows 中,所有控件(如按钮、表单……)都有一个独特的句柄。句柄用于告诉 Windows 消息外壳发送到哪个特定控件,因此我们可以将其用作调整大小检测的标准。

    MyHandle shell 包含您想要监听的窗体的窗口句柄正在调整大小。所以你应该设置它,例如在构造函数中:

    MessageFilter.MyHandle = this.Handle;
    

    现在我们创建了自己的MessageFilter,现在我们必须将它添加到您的应用程序中,以便它侦听 Windows 消息。这应该在构造函数中设置。

    MessageFilter msgFilter = new MessageFilter();
    
    Application.AddMessageFilter(msgFilter);
    

    【讨论】:

      猜你喜欢
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      相关资源
      最近更新 更多