首页 > 系统相关 >WPF中使用 WndProc 来处理Windows Messages

WPF中使用 WndProc 来处理Windows Messages

时间:2022-08-24 12:45:09浏览次数:83  
标签:IntPtr WndProc 函数 Windows void Messages MainWindow

WPF对应的C#程序有时需要与Window32程序进行通信,会使用到窗口过程函数来接受Windows消息。

  1. 引入 System.Windows.Interop 命名空间,将使用到其中的 HwndSource
  2. 使用实例如下:
// 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 文件中的几个地方调用该函数:

  1. 虚函数 protected override void OnContentRendered(EventArgs e)
  2. 虚函数 protected override void OnSourceInitialized(EventArgs e)
  3. 构造函数中,需要使异步的优先级为 Background,如下所示:
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() =>
 {
     // Todo ...
 }));
  1. 通过在注册的事件函数中,如:Application.Current.MainWindow.SourceInitialized += Window_SourceInitialized;

参考资料:
1.How to handle WndProc messages in WPF?

标签:IntPtr,WndProc,函数,Windows,void,Messages,MainWindow
From: https://www.cnblogs.com/Jeffxu/p/16619462.html

相关文章