How to get the Executable name of a window
Aaah. I read the MSDN page at the bottom.
From http://support.microsoft.com/?id=228469 (archive.org link):
GetWindowModuleFileName and GetModuleFileName correctly retrieve information about windows and modules in the calling process. In Windows 95 and 98, they return information about windows and modules in other processes. However, in Windows NT 4.0 and Windows 2000, since module handles are no longer shared by all processes as they were on Windows 95 and 98, these APIs do not return information about windows and modules in other processes.
To get more information on Windows 2000, use the Process Status Helper set of APIs (known as PSAPI, see Psapi.h include file), available since Windows NT 4.0. APIs such as GetModuleFileNameEx and GetModuleBaseName offer equivalent functionality.
Try using GetModuleFileNameEx instead.
The GetWindowModuleFileName
function works for windows in the current process only.
You have to do the following:
- Retrieve the window's process with
GetWindowThreadProcessId
. - Open the process with
PROCESS_QUERY_INFORMATION
andPROCESS_VM_READ
access rights usingOpenProcess
. - Use
GetModuleFileNameEx
on the process handle.
If you really want to obtain the name of the module with which the window is registered (as opposed to the process executable), you can obtain the module handle with GetWindowLongPtr
with GWLP_HINSTANCE
. The module handle can then be passed to the aforementioned GetModuleFileNameEx
.
Example:
TCHAR buffer[MAX_PATH] = {0};
DWORD dwProcId = 0;
GetWindowThreadProcessId(hWnd, &dwProcId);
HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ , FALSE, dwProcId);
GetModuleFileName((HMODULE)hProc, buffer, MAX_PATH);
CloseHandle(hProc);
http://support.microsoft.com/?id=228469 (archive.org link)
The executive summary is, GetWindowModuleFileName()
doesn't work for windows in other processes in NT-based Windows.
Instead, you can use QueryFullProcessImageName()
once you have a handle to the process. You can get a handle to the process with OpenProcess()
, which you can use once you have a process id. You can get the process id from the HWND by using GetWindowThreadProcessId()