有没有一种方法可以在用户控件中接收父窗体的wndproc?
我正在制作标题栏用户控件,希望能够接收关于窗体调整大小的Windows消息。
(该窗体的formborderstyle = none.)
由于 WndProc
函数并不拦截所有的窗口消息,我习惯创建一个 MessageFilter
,因为它可以过滤每一个窗口消息。所以首先您需要创建一个新的类来实现接口 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中,所有控件(如按钮、表单等)都有一个唯一的句柄(handle)。句柄用于告诉系统将Windows消息发送到哪个具体的控制项,因此我们可以将其用作调整大小检测的条件。
MyHandle
应包含您要监听其调整大小的窗体的句柄。因此,您应在构造函数中设置它,例如:
MessageFilter.MyHandle = this.Handle;
MessageFilter
,现在我们需要将其添加到您的应用程序中,使其监听Windows消息。这应该在构造函数中设置。MessageFilter msgFilter = new MessageFilter();
Application.AddMessageFilter(msgFilter);