I've written some code to get the filename of the executable from a window handle. This code works perfect, but when i turn on optimalisation on in the compiler my program crashes. I cant debug this problem since it only happens when optimalisation is turned on.
The reason why i think the problem is GetModuleFileNameExDLL, is because the program doesnt get past this line.
I am using mingw in combination with code::blocks.
Code:
void GetFilenamFromWindowHandle(HWND hwnd,char* fileName,int sizeFileName)
{
typedef DWORD (*GETMODULEFILENAMEEX) (HANDLE hProcess,HMODULE hModule,LPTSTR lpFilename,DWORD nSize);
typedef BOOL (*ENUMPROCESSMODULES) (HANDLE hProcess,HMODULE* lphModule,DWORD cb,LPDWORD lpcbNeeded);
if(isWinNT)
{
HINSTANCE psapiLib = LoadLibrary("PSAPI");
if(!psapiLib)
{
Msg("Missing or invallid psapi.dll, this program will now close.");
ExitProcess(0);
return;
}
GETMODULEFILENAMEEX GetModuleFileNameExDLL = (GETMODULEFILENAMEEX) GetProcAddress(psapiLib, "GetModuleFileNameExA");
ENUMPROCESSMODULES EnumProcessModulesDLL = (ENUMPROCESSMODULES) GetProcAddress(psapiLib, "EnumProcessModules");
if(GetModuleFileNameExDLL == 0 || EnumProcessModulesDLL == 0)
{
Msg("Missing or invallid psapi.dll, this program will now close.");
ExitProcess(0);
return;
}
HANDLE hMainProc;
DWORD procId=0;
GetWindowThreadProcessId(hwnd,&procId);
hMainProc = OpenProcess( PROCESS_QUERY_INFORMATION |PROCESS_VM_READ,false, procId );
if(!hMainProc)
return;
HMODULE mod ;
DWORD needed;
EnumProcessModulesDLL(hMainProc,&mod,sizeof(mod),&needed);
GetModuleFileNameExDLL(hMainProc,mod,fileName,sizeFileName); //something goes wrong at this call (i think)
CloseHandle(hMainProc);
}
else
{
GetWindowModuleFileName(hwnd,fileName,sizeFileName);
}
}