首页 C/C++修行正文

C++ 根据进程名称获取进程id+根据进程id获取进程路径

欲儿 C/C++修行 2020-03-16 1776 0

源代码如下:已经做成了函数,大家可以自行调用


#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;
}


版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

评论