I am trying to get the name of a window executable that is outside of my C # 2.0 application. My application is currently receiving a window handle (hWnd) using the GetForegroundWindow () call from "user32.dll".
From the digging that I was able to do, I think I want to use the GetModuleFileNameEx () function (from the PSAPI) to get the name, but GetModuleFileNameEx () requires a process handle, not a window.
Is it possible to get a process handle from a window handle? (Do I need to get a window thread handle first?)
EDIT the first sentence to clarify what I'm trying to do.
UPDATE! Here the C # code I found worked for me. The only warning is that sometimes it returns a file / path where the drive letter is "?" instead of the actual drive letter (for example, "C"). “I have not understood why.”
[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()); }
c # winapi hwnd
Pretzel Nov 10 '08 at 4:59 2008-11-10 04:59
source share