Check whether one specific process is running on windows with C++

前端 未结 3 1995
终归单人心
终归单人心 2020-12-11 21:02

Is there any function in psapi or windows.h to get desired process\' is running via only the process name (e.g : \"chrome.exe\") without getting all processes.

Edit

3条回答
  •  醉梦人生
    2020-12-11 21:54

    #include "stdafx.h"
    #include 
    #include 
    #include 
    
    using namespace std;
    
    DWORD FindProcessId(const std::wstring& processName);
    
    int main(int argc, char* argv[])
    {
    
      bool bAnyBrowserIsOpen = false;
    
      if ( FindProcessId(L"chrome.exe") || FindProcessId(L"firefox.exe") || FindProcessId(L"iexplore.exe"))
      {
         bAnyBrowserIsOpen = true;
      }
    
      return 0;
    }
    
    
    DWORD FindProcessId(const std::wstring& processName)
    {
      PROCESSENTRY32 processInfo;
      processInfo.dwSize = sizeof(processInfo);
    
      HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
      if ( processesSnapshot == INVALID_HANDLE_VALUE )
        return 0;
    
      Process32First(processesSnapshot, &processInfo);
      if ( !processName.compare(processInfo.szExeFile) )
      {
        CloseHandle(processesSnapshot);
        return processInfo.th32ProcessID;
      }
    
      while ( Process32Next(processesSnapshot, &processInfo) )
      {
        if ( !processName.compare(processInfo.szExeFile) )
        {
          CloseHandle(processesSnapshot);
          return processInfo.th32ProcessID;
        }
      }
    
      CloseHandle(processesSnapshot);
      return 0;
    }
    

提交回复
热议问题