To sum it up, I need to do this:
12345(hWnd) -> “C:\setup.exe”
Right now, I am using GetProcessImageFileName to retrieve the Kernel Device Path of a process handle. I’m retrieving the handle using OpenProcess, passing it the PID. The PID (which I also need) is being retrieved using GetWindowThreadProcessId.
However, this gets me to a string like:
\Device\Harddisk1\setup.exe
At this point, I enumerate all drives on the system using DriveInfo.GetDrives(), and then call QueryDosDevice. Finally, I can do some string-manipulation magic, and “boom,” I have my path.
Ok, so my issues:
- This process breaks down on Network drives.
- All I really want is
QueryFullProcessImageNameon XP
There HAS to be a better way to do this. Please enlighten me, oh gods of WIN32API!
The obvious question would be why you don’t just use
QueryFullProcessImageName, if that’s what you want? Do you need compatibility with older versions of Windows?The closest equivalent to
QueryFullProcessImageNamethat’s available on XP is probablyGetModuleFileNameEx. I’d probably detect whetherQueryFullProcessImageNameis available and use it if possible, otherwise fall back toGetModuleFileNameEx.Edit: While
GetModuleFileNameExisn’t 100% dependable at retrieving the name of the executable for every possible process, it does work at least a fairly substantial part of the time. Here’s a quick bit of test code I put together:The results of a quick test are somewhat interesting. Compiled as 32-bit code, the version using
QueryFullProcessImageNamefound 33 processes with top-level windows, and found names for 31 of those executables. The version usingGetModuleFileNameEx, also found 33 processes, but only found names for 21 of the executable. If, however, I compile it as 64-bit code, either version finds filenames for 31 out of 33 executables (and the same two fail). Given the frequency with which you see XP/x64, that’s probably of little consequence, but I found it interesting nonetheless.In any case, even the least capable version (32-bit/GMFNE) found names for ~2/3rds of the files. While that’s certainly not what you’d hope for, it’s certainly better than nothing.