C++通过进程名获取进程句柄

记录下一段,比较常用的代码。

#include 

//通过进程ID获取进程句柄
HANDLE GetProcessHandle(int nID)
{
	return OpenProcess(PROCESS_TERMINATE, FALSE, nID);
}

//通过进程名获取进程句柄
HANDLE GetProcessHandle(LPCWSTR lpName)
{
	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, lpName)) 
		{
			CloseHandle(hSnapshot);
			return GetProcessHandle(pe.th32ProcessID);
		}
	}
	return NULL;
}

 

你可能感兴趣的:(编程笔记)