头文件
#include <stdio.h>
#include <windows.h>
#include <process.h>
#include <tlhelp32.h>
监测进程是否存在
DWORD GetProcessIDByName(const char* pName)
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot) {
return NULL;
}
PROCESSENTRY32 pe = { sizeof(pe) };
for (BOOL ret = Process32First(hSnapshot, &pe); ret; ret = Process32Next(hSnapshot, &pe))
{
if (strcmp(pe.szExeFile, pName) == 0)
{
CloseHandle(hSnapshot);
return pe.th32ProcessID;
}
}
CloseHandle(hSnapshot);
return 0;
}
监测多个同名进程
int getProcessHandle(LPCWSTR lpName, HANDLE pH[20])
{
int num = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot)
{
return 0;
}
PROCESSENTRY32 pe = { sizeof(pe) };
BOOL fOk;
for (fOk = Process32First(hSnapshot, &pe); fOk; fOk = Process32Next(hSnapshot, &pe))
{
if (!_tcsicmp(pe.szExeFile, lpName))
{
pH[num++] = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
}
}
CloseHandle(hSnapshot);
return num;
}