根据进程ID获取进程路径
根据进程ID获取进程路径有两种方法:
方法1:OpenProcess --> GetModuleFileNameEx
方法2:OpenProcess --> EnumProcessModules --> GetModuleFileNameEx
注意事项:
1、使用GetModuleFileNameEx()而不是GetModuleFileName()
2、GetModuleFileNameEx()指定的hProcess需要PROCESS_QUERY_INFORMATION | PROCESS_VM_READ权限
3、函数使用细节参考MSDN
代码片段:
HWND hWnd = FindWindow(NULL, _T("计算器")); if (hWnd != NULL) { DWORD dwProcID = 0; ::GetWindowThreadProcessId(hWnd, &dwProcID); HMODULE hProcess = (HMODULE)OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, dwProcID); if (hProcess != NULL) { CString strLog; // 方法1:OpenProcess --> GetModuleFileNameEx TCHAR szPath[MAX_PATH]; //DWORD dwRet = GetModuleFileName(hProcess, szPath, MAX_PATH); DWORD dwRet = GetModuleFileNameEx(hProcess, NULL, szPath, MAX_PATH); if (dwRet == 0) { strLog.Format(_T("[Method1] GetModuleFileNameEx failed. errcode:%d\n"), ::GetLastError()); OutputDebugString(strLog); } else { strLog.Format(_T("[Method1] GetModuleFileNameEx get path %s\n"), szPath); OutputDebugString(strLog); } // 方法2:OpenProcess --> EnumProcessModules --> GetModuleFileNameEx HMODULE hMod = NULL; DWORD cb = 0; if (EnumProcessModules((HANDLE)hProcess, &hMod, sizeof(hMod), &cb)) { //dwRet = GetModuleFileName(hMod, szPath, MAX_PATH); dwRet = GetModuleFileNameEx(hProcess, hMod, szPath, MAX_PATH); if (dwRet == 0) { strLog.Format(_T("[Method2] GetModuleFileNameEx failed. errcode:%d\n"), ::GetLastError()); OutputDebugString(strLog); } else { strLog.Format(_T("[Method2] GetModuleFileNameEx get path %s\n"), szPath); OutputDebugString(strLog); } // 不要对hMod调用CloseHandle } else { strLog.Format(_T("[Method2] EnumProcessModules failed. errcode:%d\n"), ::GetLastError()); OutputDebugString(strLog); } ::CloseHandle(hProcess); } }
输出结果:
[Method1] GetModuleFileNameEx get path C:\Windows\system32\calc.exe
[Method2] GetModuleFileNameEx get path C:\Windows\system32\calc.exe
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity. We had everything before us, we had nothing before us.
这是最好的时代,这是最坏的时代;这是智慧的年代,这是愚蠢的年代;这是信仰的时期,这是怀疑的时期;我们的前途拥有一切,我们的前途一无所有。
这是最好的时代,这是最坏的时代;这是智慧的年代,这是愚蠢的年代;这是信仰的时期,这是怀疑的时期;我们的前途拥有一切,我们的前途一无所有。