如何获得Window实例的hWnd?

我的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; 

根据Douglas的回答,如果Window还没有显示出来,它可能没有HWND。 您可以在使用EnsureHandle()显示窗口之前强制创build一个:

 var window = Window.GetWindow(element); IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle(); 

请注意, Window.GeWindow可以返回null ,所以你也应该真的testing一下。