59

我的 WPF 应用程序有多个窗口,我需要能够获取每个 Window 实例的 hWnd 以便我可以在 Win32 API 调用中使用它们。

我想做的例子:

Window myCurrentWindow = Window.GetWindow(this);
IntPtr myhWnd = myCurrentWindow.hWnd; // Except this property doesn't exist.

最好的方法是什么?

4

2 回答 2

84

WindowInteropHelper是你的朋友。它有一个接受Window参数的构造函数和一个Handle返回其窗口句柄的属性。

Window window = Window.GetWindow(this);
var wih = new WindowInteropHelper(window);
IntPtr hWnd = wih.Handle;
于 2012-05-20T17:02:36.943 回答
23

扩展道格拉斯的答案,如果Window尚未显示,它可能没有 HWND。您可以使用以下命令强制在窗口显示之前创建一个EnsureHandle()

var window = Window.GetWindow(element);

IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();

注意Window.GeWindowcan return null,所以你也应该真正测试一下。

于 2016-10-06T12:18:10.290 回答