直接看代码
#include <iostream>
#include <string>
#include <windows.h>
#include <tlhelp32.h> //进程快照函数头文件
#include <Psapi.h>
using namespace std;
std::string tcharToString(const TCHAR* tcharStr)
{
int len = WideCharToMultiByte(CP_UTF8, 0, tcharStr, -1, NULL, 0, NULL, NULL);
char* buf = new char[len];
WideCharToMultiByte(CP_UTF8, 0, tcharStr, -1, buf, len, NULL, NULL);
std::string str(buf);
delete[] buf;
return str;
}
std::string GetProcessPathByName(const std::string& processName) {
DWORD processIds[1024], cbNeeded, cProcesses;
if (!EnumProcesses(processIds, sizeof(processIds), &cbNeeded)) {
return "";
}
cProcesses = cbNeeded / sizeof(DWORD);
for (DWORD i = 0; i < cProcesses; i++) {
if (processIds[i] != 0) {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processIds[i]);
if (hProcess != NULL) {
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
DWORD cbSize = sizeof(szProcessName) / sizeof(TCHAR);
if (QueryFullProcessImageName(hProcess, 0, szProcessName, &cbSize) != 0) {
std::string processPath = tcharToString(szProcessName);
size_t pos = processPath.find_last_of("\\");
std::string name = processPath.substr(pos + 1);
if (name == processName) {
CloseHandle(hProcess);
return processPath;
}
}
CloseHandle(hProcess);
}
}
}
return "";
}
int main()
{
cout << GetProcessPathByName("acad.exe");
system("pause");
}
GetProcessPathByName 调用传入需要查询的进程名称,如果该进程在启动中,则返回该进程的路径,否则返回""。