根据进程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
原文:http://www.cnblogs.com/shokey520/p/3790333.html