且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 WPF 中处理 WndProc 消息?

更新时间:2023-08-23 14:47:58

实际上,据我所知,使用 HwndSourceHwndSourceHook 在 WPF 中确实可以实现这样的事情.请参阅 MSDN 上的此主题 为例.(相关代码如下)

Actually, as far as I understand such a thing is indeed possible in WPF using HwndSource and HwndSourceHook. See this thread on MSDN as an example. (Relevant code included below)

// 'this' is a Window
HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));

private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
    //  do stuff

    return IntPtr.Zero;
}

现在,我不太确定您为什么要在 WPF 应用程序中处理 Windows Messaging 消息(除非它是与另一个 WinForms 应用程序一起工作的最明显的互操作形式).WPF 中的设计思想和 API 的性质与 WinForms 非常不同,因此我建议您更多地熟悉 WPF,以确切了解为什么没有等效的 WndProc.

Now, I'm not quite sure why you'd want to handle Windows Messaging messages in a WPF application (unless it's the most obvious form of interop for working with another WinForms app). The design ideology and the nature of the API is very different in WPF from WinForms, so I would suggest you just familiarise yourself with WPF more to see exactly why there is no equivalent of WndProc.