如何在Windows中使用C++从PID获取进程名?
发布于 2010-12-31 20:56:24
您可以在拥有进程句柄后,使用WIN32接口GetModuleBaseName获取进程名称。您可以使用OpenProcess获取进程句柄。
要获得可执行文件的名称,您还可以使用GetProcessImageFileName。
发布于 2018-08-24 14:09:33
以上所有方法都需要加载psapi.dll (Read the remarks section),并且从效率的角度来看,为了获得可执行文件的名称,甚至不应该考虑遍历进程快照。
即使根据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;
}
发布于 2010-12-31 20:52:38
如果您正在尝试获取给定进程的可执行映像名称,请查看GetModuleFileName。
https://stackoverflow.com/questions/4570174
复制相似问题