我的WPF应用程序有多个窗口,我需要能够获取每个窗口实例的hWnd,以便我可以在Win32 API调用中使用它们。
我想要做的一个示例:
Window myCurrentWindow = Window.GetWindow(this);
IntPtr myhWnd = myCurrentWindow.hWnd; // Except this property doesn't exist.
怎样才能做到最好?
我的WPF应用程序有多个窗口,我需要能够获取每个窗口实例的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;
扩展Douglas的答案,如果Window
还没有被显示,可能没有HWND。 你可以在窗口显示之前使用EnsureHandle()
强制创建一个:
var window = Window.GetWindow(element);
IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();
请注意,Window.GeWindow
可能会返回 null
,因此您确实需要对其进行测试。