我的WPF應用程序有多個窗口,我需要能夠獲取每個Window實例的hWnd,以便我可以在Win32 API調用中使用它們。如何獲取Window實例的hWnd?
什麼例子我想這樣做:
Window myCurrentWindow = Window.GetWindow(this);
IntPtr myhWnd = myCurrentWindow.hWnd; // Except this property doesn't exist.
什麼是做到這一點的最好方法是什麼?
我的WPF應用程序有多個窗口,我需要能夠獲取每個Window實例的hWnd,以便我可以在Win32 API調用中使用它們。如何獲取Window實例的hWnd?
什麼例子我想這樣做:
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;
擴展道格拉斯的答案,如果Window
尚未顯示,它可能沒有HWND。您可以強制使用EnsureHandle()
顯示在窗口前一個要創建:
var window = Window.GetWindow(element);
IntPtr hWnd = new WindowInteropHelper(window).EnsureHandle();
注意Window.GeWindow
可以返回null
,所以你應該真正測試過。
可能重複[是否有可能獲得WPF Popup控件的Hwnd?](http://stackoverflow.com/questions/7815121/is-it-possible-to-get-the-hwnd-of- a-wpf-popup-control) –
@HansPassant:另一個問題涉及彈出控件,而不是實際的窗口。 (是的,這個問題也是間接的答案,但它不是重複的。) – Douglas