通过进程名称,获取其路径

使用windows api

#include <psapi.h>
#include <tlhelp32.h>
 
void get_process_file_path(DWORD process_id, char* path, int path_size)
{
    HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id);
    GetModuleFileNameExA(process, NULL, path, path_size);
    CloseHandle(process);
}
 
 
bool get_exe_path(LPCWSTR processName, char* path, int path_size)
{
    PROCESSENTRY32 processInfo;
    processInfo.dwSize = sizeof(processInfo);
 
    HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    if (processesSnapshot == INVALID_HANDLE_VALUE)
    {
        printf("Invalid handle value\n");
        return false;
    }
 
    Process32First(processesSnapshot, &processInfo);
    if (!wcscmp(processName, processInfo.szExeFile))
    {
        CloseHandle(processesSnapshot);
        printf("Found process\n");
        return true;
    }
 
    while (Process32Next(processesSnapshot, &processInfo))
    {
        if (!wcscmp(processName, processInfo.szExeFile))
        {
            DWORD pid = processInfo.th32ProcessID;
            CloseHandle(processesSnapshot);
            get_process_file_path(pid, path, path_size);
            return true;
        }
    }
 
    CloseHandle(processesSnapshot);
    printf("Process NOT found.\n");
    return false;
}

此处要轮询每个进程,稍微费时,不适合几秒钟就做一次的情况

posted on 2019-01-23 16:39  liujx2019  阅读(297)  评论(0编辑  收藏  举报

导航