How to get the Executable name of a window

The GetWindowModuleFileName function works for windows in the current process only.

You have to do the following:

  1. Retrieve the window’s process with GetWindowThreadProcessId.
  2. Open the process with PROCESS_QUERY_INFORMATION and PROCESS_VM_READ access rights using OpenProcess.
  3. 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);

Leave a Comment