要获取某个进程的句柄,首先要获取该进程的ID,通过ID获取进程的句柄。代码如下:
需要用到的头文件:
#include "tlhelp32.h"
#include "windows.h"
DWORD GetProcessidByName(const wchar_t* name)
{
DWORD id = 0;
HANDLE hSnapshot = INVALID_HANDLE_VALUE;
try
{
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if (INVALID_HANDLE_VALUE == hSnapshot)
{
printf("CreateToolhelp32Snapshot fail, error:[%d]", GetLastError());
throw 0;
}
if (!Process32First(hSnapshot, &pe))
{
printf("Process32First fail, error:[%d]", GetLastError());
throw 0;
}
do
{
if (wcscmp(pe.szExeFile, name)==0)
{
id = pe.th32ProcessID;
break;
}
} while (Process32Next(hSnapshot, &pe));
if (INVALID_HANDLE_VALUE != hSnapshot)
{
CloseHandle(hSnapshot);
hSnapshot = INVALID_HANDLE_VALUE;
}
}
catch (...)
{
if (INVALID_HANDLE_VALUE != hSnapshot)
{
CloseHandle(hSnapshot);
hSnapshot = INVALID_HANDLE_VALUE;
}
id = 0;
}
return id;
}
HANDLE GetProcessHandleByID(int nID)//通过进程ID获取进程句柄
{
return OpenProcess(PROCESS_ALL_ACCESS, FALSE, nID);
}