[英]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.