C++代码无痕读取app进程pid
时间: 2023-07-11 21:05:01 浏览: 40
要无痕读取一个进程的PID,可以使用Windows API函数EnumProcesses()和OpenProcess()。
以下是一个示例代码,可以读取指定应用程序的PID:
```cpp
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
DWORD GetProcessId(LPCTSTR szProcessName)
{
DWORD dwProcessId = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe32 = { 0 };
pe32.dwSize = sizeof(pe32);
if (Process32First(hSnapshot, &pe32))
{
do
{
if (_tcsicmp(pe32.szExeFile, szProcessName) == 0)
{
dwProcessId = pe32.th32ProcessID;
break;
}
} while (Process32Next(hSnapshot, &pe32));
}
CloseHandle(hSnapshot);
}
return dwProcessId;
}
int main()
{
DWORD dwPid = GetProcessId(_T("notepad.exe"));
if (dwPid != 0)
{
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, dwPid);
if (hProcess != NULL)
{
// do something with the process
CloseHandle(hProcess);
}
}
return 0;
}
```
在这个例子中,GetProcessId()函数使用CreateToolhelp32Snapshot()枚举所有进程,并查找指定应用程序的进程ID。如果找到了进程ID,OpenProcess()函数将打开该进程的句柄,可以使用这个句柄进行进程操作。