源代码如下:已经做成了函数,大家可以自行调用
#include <windows.h>
#include <stdint.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <windows.h>
#include <Psapi.h>
#include <iostream>
#include <vector>
#include<string>
#include<iostream>
using namespace std;
typedef struct EnumHWndsArg
{
std::vector<HWND> *vecHWnds;
DWORD dwProcessId;
}EnumHWndsArg, *LPEnumHWndsArg;
DWORD GetProcessIDByName(const char* pName)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot) {
return NULL;
}
PROCESSENTRY32 pe = { sizeof(pe) };
for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe)) {
if (strcmp(pe.szExeFile, pName) == 0) {
CloseHandle(hSnapshot);
return pe.th32ProcessID;
}
//printf("%-6d %s\n", pe.th32ProcessID, pe.szExeFile);
}
CloseHandle(hSnapshot);
return 0;
}
string GetProcessFilePath(DWORD process_id)
{
HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id);
if (process == NULL)
return string();
char file_path[MAX_PATH] = { 0 };
GetModuleFileNameEx(process, NULL, file_path, MAX_PATH);
CloseHandle(process);
return string(file_path);
}
int main()
{
const char * a = "CosClient.exe";//申明进程的名称
DWORD pid = GetProcessIDByName(a);//获取PID
string path = GetProcessFilePath(pid);//通过PID获取进程路径
while(true);
return 0;
}
发表评论: