c++ win32 遍历进程列表

使用 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\t%ls\n", 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\t%ls\n", pid, szProcessName);
      CloseHandle(hProcess);
    }
  }
  return 0;
}
posted @ 2021-08-03 16:31  Ajanuw  阅读(432)  评论(0编辑  收藏  举报