WPF中使用 WndProc 来处理Windows Messages
WPF对应的C#程序有时需要与Window32程序进行通信,会使用到窗口过程函数来接受Windows消息。
- 引入
System.Windows.Interop
命名空间,将使用到其中的HwndSource
- 使用实例如下:
// Add an event handler that receives all window messages,
// 该函数的调用必须要当前程序的 MainWindow 初始化之后
public void AddHookWndProc(Window curWindow)
{
if(curWindow!=null)
{
IntPtr hwnd = new WindowInteropHelper(curWindow).Handle;
HwndSource.FromHwnd(hwnd).AddHook(WndProc);
}
}
// 窗口过程函数,用来接受处理Windows消息
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// Todo: Handle the received message.
return IntPtr.Zero;
}
【注意】:public void AddHookWndProc(Window curWindow)
函数需要在当前App的MainWindow 初始化之后才可以进行,否则 hwnd 将出现null异常。一般可以在 MainWindow.xaml.cs 文件中的几个地方调用该函数:
- 虚函数
protected override void OnContentRendered(EventArgs e)
- 虚函数
protected override void OnSourceInitialized(EventArgs e)
- 构造函数中,需要使异步的优先级为
Background
,如下所示:
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
{
// Todo ...
}));
- 通过在注册的事件函数中,如:
Application.Current.MainWindow.SourceInitialized += Window_SourceInitialized;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!