代码有些拙略,能够根据进程名字获取进程的全路径。但是以32位编译的代码不能获取64位进程信息,GetLastError等于299。
#include <Windows.h> #include <TlHelp32.h> #include <iostream> #include <conio.h> using namespace std; char* GetProcessPath(char* szProcessName) { PROCESSENTRY32 pe32; pe32.dwSize = sizeof(pe32); HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapShot == INVALID_HANDLE_VALUE) { cout << "CreateToolhelp32Snapshot Error" << endl; return ""; } BOOL bRet = Process32First(hSnapShot, &pe32); while(bRet) { if (_strnicmp(szProcessName, pe32.szExeFile, strlen(szProcessName)) == 0) { hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pe32.th32ProcessID); if (hSnapShot == INVALID_HANDLE_VALUE) { DWORD dwErr = GetLastError(); cout << "CreateToolhelp32Snapshot Error: " << dwErr << endl; return ""; } MODULEENTRY32 me32; me32.dwSize = sizeof(MODULEENTRY32); if (!Module32First(hSnapShot, &me32)) { DWORD dwErr = GetLastError(); cout << "Module32First error:" << dwErr << endl; return ""; } cout << "ProcessPath = " << me32.szExePath << endl; return me32.szExePath; } bRet = ::Process32Next(hSnapShot, &pe32); } } void main() { char szProcessName[MAX_PATH]; cin >> szProcessName; GetProcessPath(szProcessName); _getch(); }