项目中 需要获取指定进程的运行路径,使用GetModuleFileNameEx无法使用32位程序获取64位程序的路径,GetProcessImageFileName可以获取32位和64位程序的进程全路径,
但GetProcessImageFileName获取的路径都是包含设备名的路径,因此我们还要转换成一下.
BOOL GetProcessFullPath(DWORD dwPID, TCHAR* pszFullPath)
{
TCHAR szImagePath[MAX_PATH] = {_T("0")};
HANDLE hProcess = NULL;
if(!pszFullPath)
return FALSE;
pszFullPath[0] = '\0';
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, dwPID);
if(!hProcess)
return FALSE;
if(!GetProcessImageFileName(hProcess, szImagePath, MAX_PATH))
{
CloseHandle(hProcess);
return FALSE;
}
if(!DosPathToNtPath(szImagePath, pszFullPath))
{
CloseHandle(hProcess);
return FALSE;
}
CloseHandle(hProcess);
return TRUE;
}
BOOL DosPathToNtPath(LPTSTR pszDosPath, LPTSTR pszNtPath)
{
TCHAR szDriveStr[500] = {_T("0")};
TCHAR szDrive[3] = {};
TCHAR szDevName[100] = {};
INT cchDevName;
INT i;
//检查参数
if(!pszDosPath || !pszNtPath )
return FALSE;
//获取本地磁盘字符串
if(GetLogicalDriveStrings(sizeof(szDriveStr), szDriveStr))
{
for(i = 0; szDriveStr[i]; i += 4)
{
if(!lstrcmpi(&(szDriveStr[i]), _T("A:\\")) || !lstrcmpi(&(szDriveStr[i]), _T("B:\\")))
continue;
szDrive[0] = szDriveStr[i];
szDrive[1] = szDriveStr[i + 1];
szDrive[2] = '\0';
if(!QueryDosDevice(szDrive, szDevName, 100))//查询 Dos 设备名
return FALSE;
cchDevName = lstrlen(szDevName);
if(_tcsnicmp(pszDosPath, szDevName, cchDevName) == 0)//命中
{
lstrcpy(pszNtPath, szDrive);//复制驱动器
lstrcat(pszNtPath, pszDosPath + cchDevName);//复制路径
return TRUE;
}
}
}
lstrcpy(pszNtPath, pszDosPath);
return FALSE;
}
int test()
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot)
{
return NULL;
}
PROCESSENTRY32 pe ={0};
pe.dwSize = sizeof(PROCESSENTRY32);
BOOL fOk;
for (fOk = Process32First(hSnapshot, &pe); fOk; fOk = Process32Next(hSnapshot, &pe))
{
TCHAR szProcessName[MAX_PATH] = {0};
GetProcessFullPath(pe.th32ProcessID, szProcessName);
}
return 0;
}