如何使用C ++在Windows中从PID获取进程名称?
我猜测 OpenProcess 函数应该有帮助,假设 你的 进程具备必要的权限。获取进程句柄之后,你可以使用 GetModuleFileNameEx 函数来获取进程的完整路径(即 .exe 文件的路径)。
#include "stdafx.h"
#include "windows.h"
#include "tchar.h"
#include "stdio.h"
#include "psapi.h"
// Important: Must include psapi.lib in additional dependencies section
// In VS2005... Project > Project Properties > Configuration Properties > Linker > Input > Additional Dependencies
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE Handle = OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE,
8036 /* This is the PID, you can find one from windows task manager */
);
if (Handle)
{
TCHAR Buffer[MAX_PATH];
if (GetModuleFileNameEx(Handle, 0, Buffer, MAX_PATH))
{
// At this point, buffer contains the full path to the executable
}
else
{
// You better call GetLastError() here
}
CloseHandle(Handle);
}
return 0;
}
获得进程名称可使用WIN32 API,GetModuleBaseName,在获取进程句柄后调用。 使用OpenProcess即可获取进程句柄。
要获取可执行文件的名称,也可以使用GetProcessImageFileName。
以上所有方法都需要加载psapi.dll (请参阅备注部分), 从效率的角度考虑,迭代进程快照以获取可执行文件名称不是一个应该考虑的选项。
根据MSDN的建议,最佳方法是使用QueryFullProcessImageName。
std::string ProcessIdToName(DWORD processId)
{
std::string ret;
HANDLE handle = OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION,
FALSE,
processId /* This is the PID, you can find one from windows task manager */
);
if (handle)
{
DWORD buffSize = 1024;
CHAR buffer[1024];
if (QueryFullProcessImageNameA(handle, 0, buffer, &buffSize))
{
ret = buffer;
}
else
{
printf("Error GetModuleBaseNameA : %lu", GetLastError());
}
CloseHandle(handle);
}
else
{
printf("Error OpenProcess : %lu", GetLastError());
}
return ret;
}
std::wstring GetProcName(DWORD aPid)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE)
{
std::wcout << "can't get a process snapshot ";
return 0;
}
for(BOOL bok =Process32First(processesSnapshot, &processInfo);bok; bok = Process32Next(processesSnapshot, &processInfo))
{
if( aPid == processInfo.th32ProcessID)
{
std::wcout << "found running process: " << processInfo.szExeFile;
CloseHandle(processesSnapshot);
return processInfo.szExeFile;
}
}
std::wcout << "no process with given pid" << aPid;
CloseHandle(processesSnapshot);
return std::wstring();
}
http://msdn.microsoft.com/en-us/library/ms682629(v=vs.85).aspx
好的例子 @ http://msdn.microsoft.com/zh-cn/library/ms682623(v=vs.85).aspx
DWORD processId; GetWindowThreadProcessId(hwnd, &processId);
。 - Andreas Haferburg