[英]How to get the process name in C++
如何在Windows中使用C ++从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 。
如果您尝试获取给定进程的可执行映像名称,请查看GetModuleFileName 。
试试这个功能:
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();
}
查看工具帮助库中的enumprocess函数:
http://msdn.microsoft.com/en-us/library/ms682629(v=vs.85).aspx
好的例子@ http://msdn.microsoft.com/en-us/library/ms682623(v=vs.85).aspx
所有上述方法都需要加载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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.