C# 如何获取Window实例的hWnd?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10675305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the hWnd of Window instance?
提问by Drahcir
My WPF application has more than one window, I need to be able to get the hWnd of each Window instance so that I can use them in Win32 API calls.
我的 WPF 应用程序有多个窗口,我需要能够获取每个 Window 实例的 hWnd,以便我可以在 Win32 API 调用中使用它们。
Example of what I would like to do:
我想做的例子:
Window myCurrentWindow = Window.GetWindow(this);
IntPtr myhWnd = myCurrentWindow.hWnd; // Except this property doesn't exist.
What's the best way to do this?
做到这一点的最佳方法是什么?
采纳答案by Douglas
WindowInteropHelperis your friend. It has a constructor that accepts a Windowparameter, and a Handleproperty that returns its window handle.
WindowInteropHelper是你的朋友。它有一个接受Window参数的构造函数和一个Handle返回其窗口句柄的属性。
Window window = Window.GetWindow(this);
var wih = new WindowInteropHelper(window);
IntPtr hWnd = wih.Handle;
回答by Drew Noakes
Extending on Douglas's answer, if the Windowhas not been shown yet, it might not have an HWND. You can force one to be created before the window is shown using EnsureHandle():
扩展道格拉斯的回答,如果Window尚未显示,则可能没有 HWND。您可以使用EnsureHandle()以下命令在显示窗口之前强制创建一个:
var window = Window.GetWindow(element);
IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();
Note that Window.GeWindowcan return null, so you should really test that too.
请注意,Window.GeWindow可以返回null,因此您也应该对其进行测试。

