Advertisement
Gistrec

WinApi get process list

Nov 18th, 2018
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <windows.h>
  2. #include <stdio.h>
  3. #include <tchar.h>
  4. #include <psapi.h>
  5.  
  6. // To ensure correct resolution of symbols, add Psapi.lib to TARGETLIBS
  7. // and compile with -DPSAPI_VERSION=1
  8. void PrintProcessNameAndID( DWORD processID ) {
  9.     TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
  10.  
  11.     // Get a handle to the process.
  12.     HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
  13.                                    PROCESS_VM_READ,
  14.                                    FALSE, processID );
  15.  
  16.     // Get the process name.
  17.     if (NULL != hProcess ) {
  18.         HMODULE hMod;
  19.         DWORD cbNeeded;
  20.  
  21.         if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded)) {
  22.             GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR));
  23.         }
  24.     }
  25.  
  26.     // Print the process name and identifier.
  27.     _tprintf( TEXT("%s  (PID: %u)\n"), szProcessName, processID );
  28.  
  29.     // Release the handle to the process.
  30.     CloseHandle( hProcess );
  31. }
  32.  
  33. int main(void) {
  34.     // Get the list of process identifiers.
  35.     DWORD aProcesses[1024], cbNeeded, cProcesses;
  36.     unsigned int i;
  37.  
  38.     if (!EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded )) {
  39.         return 1;
  40.     }
  41.  
  42.  
  43.     // Calculate how many process identifiers were returned.
  44.     cProcesses = cbNeeded / sizeof(DWORD);
  45.  
  46.     // Print the name and process identifier for each process.
  47.     for (i = 0; i < cProcesses; i++) {
  48.         if (aProcesses[i] != 0) {
  49.             PrintProcessNameAndID(aProcesses[i]);
  50.         }
  51.     }
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement