[英]How to get the hWnd of Window instance?
我的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()
在顯示窗口之前強制創建一個:
var window = Window.GetWindow(element);
IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();
請注意, Window.GeWindow
可以返回null
,因此您也應該測試它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.