C# 2.0 アプリケーションの外部にあるウィンドウの実行可能ファイルの名前を取得しようとしています。私のアプリは現在、「user32.dll」から GetForegroundWindow() 呼び出しを使用してウィンドウ ハンドル (hWnd) を取得しています。
掘り下げた結果、(PSAPI の) GetModuleFileNameEx() 関数を使用して名前を取得したいと思いますが、GetModuleFileNameEx() にはウィンドウではなくプロセスへのハンドルが必要です。
ウィンドウ ハンドルからプロセス ハンドルを取得することは可能ですか? (最初にウィンドウのスレッド ハンドルを取得する必要がありますか?)
私がやろうとしていることをより明確にするために、最初の文を編集しました。
アップデート!これが私のために働いていることがわかったC#コードです。唯一の注意点は、ドライブ文字が「?」であるファイル/パスを返す場合があることです。実際のドライブ文字 (「C」など) の代わりに。-- 理由はまだわかりません。
[DllImport("user32.dll")]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId);
[DllImport("psapi.dll")]
static extern uint GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, [Out] StringBuilder lpBaseName, [In] [MarshalAs(UnmanagedType.U4)] int nSize);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);
private string GetWindowModuleFileName(IntPtr hWnd)
{
uint processId = 0;
const int nChars = 1024;
StringBuilder filename = new StringBuilder(nChars);
GetWindowThreadProcessId(hWnd, out processId);
IntPtr hProcess = OpenProcess(1040, 0, processId);
GetModuleFileNameEx(hProcess,IntPtr.Zero,filename,nChars);
CloseHandle(hProcess);
return (filename.ToString());
}