BOOL GetParentProcessFileName( DWORD dwProcessId, CString& szFileName )
{
?? ?szFileName.Empty();? ??
?? ?HANDLE hProcessSnap = ::CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
?? ?if( hProcessSnap == INVALID_HANDLE_VALUE )
?? ??? ?return FALSE;
?? ?
?? ?//find parent process id
?? ?PROCESSENTRY32 pe32 = { 0 };
?? ?pe32.dwSize = sizeof(pe32);
?? ?BOOL bContinue = ::Process32First( hProcessSnap, &pe32 );
?? ?DWORD dwParentProcessId = 0;
?? ?while( bContinue )
?? ?{
?? ??? ?if( pe32.th32ProcessID == dwProcessId )
?? ??? ?{
?? ??? ??? ?dwParentProcessId = pe32.th32ParentProcessID;
?? ??? ??? ?break;
?? ??? ?}
?? ??? ?bContinue = ::Process32Next( hProcessSnap, &pe32 );
?? ?}
?? ?::CloseHandle( hProcessSnap );
?? ?//get parent process image name
?? ?return GetProcessFileName( dwParentProcessId, szFileName );
}
BOOL GetProcessFileName( DWORD dwPID, CString& szFileName )
{
?? ?szFileName.Empty();
?? ?//get parent process image name
?? ?if( dwPID != 0 )
?? ?{
?? ??? ?HANDLE hProcessParent = ::OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwPID );
?? ??? ?if( hProcessParent != NULL )
?? ??? ?{
?? ??? ??? ?HMODULE hModule = NULL;
?? ??? ??? ?DWORD dwNeeded = 0;
?? ??? ??? ?TCHAR szBuff[MAX_PATH] = { 0 };
?? ??? ??? ?EnumProcessModules( hProcessParent, &hModule, sizeof( hModule ), &dwNeeded );
?? ??? ??? ?GetModuleFileNameEx( hProcessParent, hModule, szBuff, MAX_PATH );
?? ??? ??? ?szFileName = szBuff;
?? ??? ??? ?::CloseHandle( hProcessParent );
?? ??? ?}?? ?
?? ?}?? ?
?? ?return ( szFileName.GetLength() > 0 );
}
typedef DWORD (WINAPI *FNGETMODULEFILENAMEEX)(HANDLE, HMODULE hModule, LPTSTR, DWORD);
FNGETMODULEFILENAMEEX?? ?fnGetModuleFileNameEx = NULL;
DWORD GetModuleFileNameEx(HANDLE hProcess, HMODULE hModule, LPTSTR lpFilename, DWORD nSize)
{
?? ?if(NULL==hDll_Psapi)
?? ??? ?hDll_Psapi = LoadLibrary(_T("psapi.dll"));
?? ?if(NULL==fnGetModuleFileNameEx && hDll_Psapi)
?? ??? ?fnGetModuleFileNameEx = reinterpret_cast<FNGETMODULEFILENAMEEX>(GetProcAddress(hDll_Psapi,"GetModuleFileNameExW"));
?? ?if(fnGetModuleFileNameEx)
?? ??? ?return fnGetModuleFileNameEx(hProcess, hModule, lpFilename, nSize);
?? ?return 0;
}
typedef BOOL (WINAPI *FNENUMPROCESSMODULES)(HANDLE, HMODULE*, DWORD, LPDWORD);
FNENUMPROCESSMODULES?? ?fnEnumProcessModules = NULL;
BOOL EnumProcessModules(HANDLE hProcess, HMODULE* lphModule, DWORD cb, LPDWORD lpcbNeeded)
{
?? ?if(NULL==hDll_Psapi)
?? ??? ?hDll_Psapi = LoadLibrary(_T("psapi.dll"));
?? ?if(NULL==fnEnumProcessModules && hDll_Psapi)
?? ??? ?fnEnumProcessModules = reinterpret_cast<FNENUMPROCESSMODULES>(GetProcAddress(hDll_Psapi,"EnumProcessModules"));
?? ?if(fnEnumProcessModules)
?? ??? ?return fnEnumProcessModules(hProcess, lphModule, cb, lpcbNeeded);
?? ?return FALSE;
}
|