私のWPFアプリケーションには複数のウィンドウがあります。Win32API呼び出しで使用できるように、各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
ため、実際にそれもテストする必要があります。