我有一段代码,如:
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应用程序中复制功能。此外,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
吗?
答案 0 :(得分:4)
基本点是:除了来源AddHook
之外,您不需要任何其他内容。每个WinForm都有一个方法GetHandle()
,它将为您提供窗口/表单的句柄(并且您已经自己找到PostMessage
)。
要翻译AddHook
,您可以编写自己的类,实现IMessageFilter
(1),也可以覆盖WndProc()
(2)。
(1)将在应用程序范围内接收消息,无论您发送哪种形式,(2)仅接收覆盖该方法的特定表单的消息。
我无法找到关于WM_CALL
的任何内容,因为您必须将窗口消息指定为整数(通常为十六进制),所以这取决于您。
(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
}
}
}
答案 1 :(得分:2)
不是更多的WPF背景。但对我来说,这听起来像是在寻找NativeWindow。