WinForms相当于WPF WindowInteropHelper,HwndSource,HwndSourceHook

我有一块代码,如:

IntPtr hWnd = new WindowInteropHelper(this).Handle; HwndSource source = HwndSource.FromHwnd(hWnd); source.AddHook(new HwndSourceHook(WndProc)); NativeMethods.PostMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_CALL, IntPtr.Zero, IntPtr.Zero); 

这最初是在WPF应用程序中。 但是,我需要在WinForms应用程序中复制该function。 另外,NativeMethods.PostMessage只是映射到user32.dll PostMessage:

 [DllImport("user32")] public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); 

我可以在WinForms应用程序中使用1到1当量的WindowInteropHelper/HwndSource/HwndSourceHook吗?

基本点是:除了源中的AddHook之外,您不需要任何其他AddHook 。 每个WinForm都有一个方法GetHandle() ,它将为您提供Window / Form的句柄(并且您已经自己找到了PostMessage )。

要翻译AddHook您可以编写自己的类来实现IMessageFilter (1),也可以覆盖WndProc() (2)。
(1)将在应用程序范围内接收消息,无论您发送哪种forms,(2)仅接收覆盖该方法的特定表单的消息。

WM_CALL找到关于WM_CALL任何内容,因为您必须将窗口消息指定为整数(通常为hex),因此这取决于您。

(1):

 using System; using System.Windows.Forms; using System.Runtime.InteropServices; public partial class Form1 : Form { [DllImport("user32")] public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); //private const int WM_xxx = 0x0; //you have to know for which event you wanna register public Form1() { InitializeComponent(); IntPtr hWnd = this.Handle; Application.AddMessageFilter(new MyMessageFilter()); PostMessage(hWnd, WM_xxx, IntPtr.Zero, IntPtr.Zero); } } class MyMessageFilter : IMessageFilter { //private const int WM_xxx = 0x0; public bool PreFilterMessage(ref Message m) { if (m.Msg == WM_xxx) { //code to handle the message } return false; } } 

(2):

 using System; using System.Windows.Forms; using System.Runtime.InteropServices; public partial class Form 1 { [DllImport("user32")] public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); //private const int WM_xxx = 0x0; //you have to know for which event you wanna register public Form1() { InitializeComponent(); IntPtr hWnd = this.Handle; PostMessage(hWnd, WM_xxx, IntPtr.Zero, IntPtr.Zero); } protected override void WndProc(ref Message m) { if (m.Msg == WMK_xxx) { //code to handle the message } } } 

不是WPF的背景。 但对我来说,这听起来像是在寻找NativeWindow 。