Sunday, March 23, 2008

Find which dll / exe created a window.

The GetWindowModuleFileName() functions can be used to find which exe or dll have created a window. But the problem with this function is that, it will not work across process.

When ever we create a window, we have to pass the an HINSTANCE into it. And later we can use GetWindowLong to get that HINSTANCE. Actually the HINSTANCE is noting but the HMODULE itself. So if we get the hinstance of a window, we can pass this handle to the
GetModuleFileNameEx() and simply get the name of the window from other processes also.


CString MyGetWindowModuleFileName( HANDLE hwindowhandle )
{
CString csModuleName;
DWORD dwProcessId;
GetWindowThreadProcessId( hwindowhandle, &dwProcessId );
HINSTANCEhModule = (HINSTANCE)GetWindowLong( hwindowhandle, GWL_HINSTANCE );
if(hModule == NULL)
{
return csModuleName;
}
HANDLE hProcess = OpenProcess(PROCESS_VM_READPROCESS_QUERY_INFORMATION, FALSE, dwProcessId );
if( hProcess == NULL )
{
return csModuleName;
}
BOOL bReturn = GetModuleFileNameEx( hProcess, hModule, csModuleName.GetBuffer( MAX_PATH), MAX_PATH );
csModuleName.ReleaseBuffer();
CloseHandle(hProcess);
return csModuleName;
}