进程遍历

1. CreateToolhelp32Snapshot()、Process32First()和Process32Next()

void ProcessSnapshot()
{
	PROCESSENTRY32 pe32;
	pe32.dwSize = sizeof(pe32);
	HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hProcessSnapshot == INVALID_HANDLE_VALUE)
	{
		return;
	}

	bool bRet = Process32First(hProcessSnapshot, &pe32);
	while (bRet)
	{
		std::wcout << "Process Name:" << pe32.szExeFile << "\t Process ID:" << pe32.th32ProcessID << std::endl;

		bRet = Process32Next(hProcessSnapshot, &pe32);
	}
	CloseHandle(hProcessSnapshot);
}

 

2. EnumProcesses()、EnumProcessModules()、GetModuleBaseName()

void MyEnumProcess()
{
	//   保存进程id数组  实际进程id所占的字节数   进程数量
	DWORD szProcesseId[1024], dwNeeded, dwProcesses;
	unsigned int i;

	if (!EnumProcesses(szProcesseId, sizeof(szProcesseId), &dwNeeded))       //枚举进程
	{
		return;
	}
		
	dwProcesses = dwNeeded / sizeof(DWORD);             //计算进程个数
	for (i = 0; i < dwProcesses; i++)
	{
		if (szProcesseId[i] != 0)
		{

			TCHAR szProcessName[MAX_PATH] = { 0 };
			HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, szProcesseId[i]);     //获得进程句柄

			if (NULL != hProcess)
			{
				HMODULE hMod;
				DWORD cbNeeded;

				if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))        //枚举进程模块信息
				{
					GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName) / sizeof(TCHAR));       //取得主模块全名,每个进程第一模块则为进程主模块
				}
			}
			std::wcout << "Process Name:" << szProcessName << "\t Process ID:" << szProcesseId[i] << std::endl;
			//_tprintf(TEXT("%s  (PID: %u)\n"), szProcessName, szProcesseId[i]);     //输出进程名及PID
			CloseHandle(hProcess);
		}
	}
		
}

 

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页