通过进程名获得进程ID

View Code
#include<windows.h>
#include<iostream>
#include<tlhelp32.h>
#include<TCHAR.h>
using namespace std;
HANDLE GetProcessHandle(int nID)//通过进程ID获取进程句柄
{
return OpenProcess(PROCESS_ALL_ACCESS, FALSE, nID);
}
HANDLE GetProcessHandle(LPCTSTR pName)//通过进程名获取进程句柄
{
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hSnapshot) {
return NULL;
}
PROCESSENTRY32 pe = { sizeof(pe) };
BOOL fOk;
for (fOk = Process32First(hSnapshot, &pe); fOk; fOk = Process32Next(hSnapshot, &pe)) {
if (!_tcscmp(pe.szExeFile, pName)) {
CloseHandle(hSnapshot);
return GetProcessHandle(pe.th32ProcessID);
}
}
return NULL;
}
int main()
{
HANDLE h=GetProcessHandle("taskmgr.exe");
if(h==NULL)
{
printf("no");
}
else
{
printf("yes");
}
return 0;
}

 

你可能感兴趣的:(进程)