码迷,mamicode.com
首页 > Windows程序 > 详细

Windows获取进程完整路径

时间:2018-10-12 21:12:42      阅读:44      评论:0      收藏:0      [点我收藏+]

标签:set   字节   imp   sid   lc_all   name   RoCE   std   驱动   

#include <stdio.h>
#include <locale.h>
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <Psapi.h>
#pragma comment (lib,"Psapi.lib")


BOOL DosPathToNtPath(LPTSTR pszDosPath, LPTSTR pszNtPath)
{
    TCHAR            szDriveStr[500];
    TCHAR            szDrive[3];
    TCHAR            szDevName[100];
    INT                iDevName;
    INT                i;

    //检查参数
    if (!pszDosPath || !pszNtPath)
        return FALSE;

    //获取本地磁盘所有盘符,以‘\0‘分隔,所以下面+4
    if (GetLogicalDriveStrings(sizeof(szDriveStr), szDriveStr))
    {
        for (i = 0; szDriveStr[i]; i += 4)
        {
            if (!lstrcmpi(&(szDriveStr[i]), _T("A:\\")) || !lstrcmpi(&(szDriveStr[i]), _T("B:\\")))
                continue;    //从C盘开始

            //盘符
            szDrive[0] = szDriveStr[i];
            szDrive[1] = szDriveStr[i + 1];
            szDrive[2] = \0;
            if (!QueryDosDevice(szDrive, szDevName, 100))//查询 Dos 设备名(盘符由NT查询DOS)
                return FALSE;

            iDevName = lstrlen(szDevName);
            if (_tcsnicmp(pszDosPath, szDevName, iDevName) == 0)//是否为此盘
            {
                lstrcpy(pszNtPath, szDrive);//复制驱动器
                lstrcat(pszNtPath, pszDosPath + iDevName);//复制路径

                return TRUE;
            }
        }
    }

    lstrcpy(pszNtPath, pszDosPath);

    return FALSE;
}
//获取进程完整路径
BOOL GetProcessFullPath(DWORD dwPID)
{
    TCHAR        szImagePath[MAX_PATH];
    TCHAR        pszFullPath[MAX_PATH];
    HANDLE        hProcess;
    if (!pszFullPath)
        return FALSE;

    pszFullPath[0] = \0;

    hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, dwPID);    //由线程ID获得线程信息
    if (!hProcess)
        return FALSE;

    if (!GetProcessImageFileName(hProcess, szImagePath, MAX_PATH))    //得到线程完整DOS路径
    {
        CloseHandle(hProcess);
        return FALSE;
    }
    if (!DosPathToNtPath(szImagePath, pszFullPath))    //DOS路径转NT路径
    {
        CloseHandle(hProcess);
        return FALSE;
    }



    CloseHandle(hProcess);

    _tprintf(_T("%5d  %s \r\n"), dwPID, pszFullPath);
    return TRUE;
}
int main(int argc, char* argv[])
{
    setlocale(LC_ALL, "chs");    //不设置解析中文字符时可能会出问题
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);    //得到系统所