如何获取窗口实例的hWnd?

61

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

我想要做的一个示例:

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

怎样才能做到最好?


2
可能是Is it possible to get the Hwnd of a WPF Popup control?的重复问题。 - Hans Passant
2
@HansPassant:另一个问题涉及弹出控件,而不是实际的窗口。(是的,这个问题也在其中间接回答了,但它不是重复的。) - Douglas
2个回答

92

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

Window window = Window.GetWindow(this);
var wih = new WindowInteropHelper(window);
IntPtr hWnd = wih.Handle;

24

扩展Douglas的答案,如果Window还没有被显示,可能没有HWND。 你可以在窗口显示之前使用EnsureHandle()强制创建一个:

var window = Window.GetWindow(element);

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

请注意,Window.GeWindow 可能会返回 null,因此您确实需要对其进行测试。


我觉得这些检查很少有用,通常你只需要把你的代码放在你确定窗口句柄存在的地方。最明显的方法是使用Loaded事件。 - MikeKulls

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接