通过GetProcessImageFileName函数获取进程路径

由于函数GetModuleFileName() 和 函数GetModuleFileNameEx()都是通过PEB头信息获取进程文件路径,所以它们只能工作于与调用进程相同位数的进程,比如:调用进程32位时,这两个函数只对32位进程有效,64位同理。所以在64位进程与32位进程并存的64位机器中,只能通过GetProcessImageFileName()函数获取进程的DOS文件路径,再通过与LogicalDriveStrings比对拼接出进程可执行文件的完整路径,方法如下:

#include <Psapi.h>

/* 功 能:获取指定进程所对应的可执行(EXE)文件全路径 * 参 数:hProcess - 进程句柄。必须具有PROCESS_QUERY_INFORMATION 或者 PROCESS_QUERY_LIMITED_INFORMATION 权限 * sFilePath - 进程句柄hProcess所对应的可执行文件路径 * 返回值: */
void GetProcessFilePath(IN HANDLE hProcess, OUT CString& sFilePath)
{
    sFilePath = _T("");
    TCHAR tsFileDosPath[MAX_PATH + 1];
    ZeroMemory(tsFileDosPath, sizeof(TCHAR)*(MAX_PATH + 1));
    if (0 == GetProcessImageFileName(hProcess, tsFileDosPath, MAX_PATH + 1))
    {
        return;
    }

    // 获取Logic Drive String长度
    UINT uiLen = GetLogicalDriveStrings(0, NULL);
    if (0 == uiLen)
    {
        return;
    }

    PTSTR pLogicDriveString = new TCHAR[uiLen + 1];
    ZeroMemory(pLogicDriveString, uiLen + 1);
    uiLen = GetLogicalDriveStrings(uiLen, pLogicDriveString);
    if (0 == uiLen)
    {
        delete[]pLogicDriveString;
        return;
    }

    TCHAR szDrive[3] = TEXT(" :");
    PTSTR pDosDriveName = new TCHAR[MAX_PATH];
    PTSTR pLogicIndex = pLogicDriveString;

    do
    {
        szDrive[0] = *pLogicIndex;
        uiLen = QueryDosDevice(szDrive, pDosDriveName, MAX_PATH);
        if (0 == uiLen)
        {
            if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
            {
                break;
            }

            delete[]pDosDriveName;
            pDosDriveName = new TCHAR[uiLen + 1];
            uiLen = QueryDosDevice(szDrive, pDosDriveName, uiLen + 1);
            if (0 == uiLen)
            {
                break;
            }
        }

        uiLen = _tcslen(pDosDriveName);
        if (0 == _tcsnicmp(tsFileDosPath, pDosDriveName, uiLen))
        {
            sFilePath.Format(_T("%s%s"), szDrive, tsFileDosPath + uiLen);
            break;
        }

        while (*pLogicIndex++);
    } while (*pLogicIndex);

    delete[]pLogicDriveString;
    delete[]pDosDriveName;
}

你可能感兴趣的:(进程路径)