我的WPF应用程序有多个窗口,我需要能够获取每个Window实例的hWnd,以便我可以在Win32 API调用中使用它们.
我想做的例子:
Window myCurrentWindow = Window.GetWindow(this);
IntPtr myhWnd = myCurrentWindow.hWnd; // Except this property doesn't exist.
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?
Dou*_*las 70
WindowInteropHelper是你的朋友.它有一个接受Window参数的构造函数,以及一个Handle返回其窗口句柄的属性.
Window window = Window.GetWindow(this);
var wih = new WindowInteropHelper(window);
IntPtr hWnd = wih.Handle;
Run Code Online (Sandbox Code Playgroud)
Dre*_*kes 13
根据道格拉斯的回答,如果Window还没有显示,它可能没有HWND.您可以在使用EnsureHandle()以下方法显示窗口之前强制创建一个:
var window = Window.GetWindow(element);
IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();
Run Code Online (Sandbox Code Playgroud)
请注意,Window.GeWindow可以返回null,所以你也应该测试一下.
| 归档时间: |
|
| 查看次数: |
50266 次 |
| 最近记录: |