Thursday, November 15, 2007

Get the name of the EXE associated with a given window

Here is one method to find the EXE name corresponding to a window with given handle:

#include

HANDLE hProc;

HMODULE ahMod [10];

DWORD dwNeeded;

DWORD dwPid;

BOOL bResult = FALSE;

char * pszFilename = new char[ MAX_PATH ];

HWND hWnd = ( HWND )0x0003064C; // Window handle obtained using the Spy++ tool. Replace this with appropriate value.

// Get ProcessID corresponding to this window handle.

GetWindowThreadProcessId ( hWnd, &dwPid);

hProc = OpenProcess (PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,

FALSE,

dwPid);

if (hProc)

{

if (EnumProcessModules(hProc, ahMod, sizeof(ahMod), &dwNeeded))

{

// we're only interested in the first module.

// pszFilename will contain the EXE name.

if (GetModuleBaseName(hProc, ahMod[0], pszFilename, MAX_PATH ))

{

bResult = TRUE;

}

}

CloseHandle (hProc);

}

Note : Psapi.lib should be included in the project settings.

EnumProcessModules() function stores a handle for each module in the specified process to the specified array. Out of these, the first handle will be the handle of the application. The rest will be other modules loaded in the process. So you can also use this code to find the modules associated with a specific process.

No comments: