我的 WPF 应用程序有多个窗口,我需要能够获取每个 Window 实例的 hWnd 以便我可以在 Win32 API 调用中使用它们。
我想做的例子:
Window myCurrentWindow = Window.GetWindow(this);
IntPtr myhWnd = myCurrentWindow.hWnd; // Except this property doesn't exist.
最好的方法是什么?
WindowInteropHelper
是你的朋友。它有一个接受Window
参数的构造函数和一个Handle
返回其窗口句柄的属性。
Window window = Window.GetWindow(this);
var wih = new WindowInteropHelper(window);
IntPtr hWnd = wih.Handle;
扩展道格拉斯的答案,如果Window
尚未显示,它可能没有 HWND。您可以使用以下命令强制在窗口显示之前创建一个EnsureHandle()
:
var window = Window.GetWindow(element);
IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();
注意Window.GeWindow
can return null
,所以你也应该真正测试一下。