• 周日. 10 月 6th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

c++ win32 遍历进程列表

admin

11 月 28, 2021

使用 CreateToolhelp32Snapshot

#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
#include <Psapi.h>

int main() {
  HANDLE hSnap = CreateToolhelp32Snapshot(PROCESS_ALL_ACCESS, 0);
  if (hSnap != INVALID_HANDLE_VALUE)
  {
    PROCESSENTRY32 pe;
    pe.dwSize = sizeof(pe);
    if (Process32First(hSnap, &pe))
    {
      do {
        printf("PID: %X	%ls
", pe.th32ProcessID, pe.szExeFile);
      } while (Process32Next(hSnap, &pe));
    }
  }
  CloseHandle(hSnap);
  return 0;
}

使用 EnumProcesses

#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
#include <Psapi.h>

int main() {
  DWORD aProcesses[1024], cbNeeded, cProcesses;
  size_t i;
  if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
  {
    return 1;
  }
  cProcesses = cbNeeded / sizeof(DWORD);
  for (i = 0; i < cProcesses; i++)
  {
    if (aProcesses[i] != 0)
    {
      DWORD pid = aProcesses[i];
      TCHAR szProcessName[MAX_PATH] = TEXT("???");
      HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pid);
      if (NULL != hProcess)
      {
        HMODULE hMod;
        DWORD cbNeeded;
        if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
        {
          GetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName) / sizeof(TCHAR));
        }
      }
      printf("PID: %X	%ls
", pid, szProcessName);
      CloseHandle(hProcess);
    }
  }
  return 0;
}

发表回复