获取浏览器进程ID,然后在C++程序中使用

Getting a browser process ID and then using it in the program in C++

我正在尝试为浏览器(Chrome 和 Firefox)创建一个简单的单词荧光笔,我希望我的程序使用进程名称(chrome.exefirefox.exe)并且然后得到他们的进程ID。

我找到了可以获取进程 ID 的代码,但它需要用户手动输入进程名称:

#include "pch.h"
#include <iostream>
#include <string>
#include <windows.h>
#include <tlhelp32.h>

DWORD FindProcessId(const std::wstring& processName);

int main()
{
   std::wstring processName;

   std::wcout << "Enter the process name: ";
   std::getline(std::wcin, processName);

   DWORD processID = FindProcessId(processName);

   if (processID == 0)
      std::wcout << "Could not find " << processName.c_str() << std::endl;
   else
      std::wcout << "Process ID is " << processID << std::endl;

   system("PAUSE");
   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;
}

现在,有没有办法通过检查用户是 运行 firefox.exe 还是 chrome.exe 来操纵此代码以自动获取进程 ID?

获取进程 ID 后,如何让我的程序明白它需要关注所述 ID?

Now, is there a way to manipulate this code for it to get the process ID automatically by checking whether the user is running firefox.exe or chrome.exe?

#include <iostream>
#include <string>
#include <windows.h>
#include <tlhelp32.h>

DWORD FindProcessId(const std::wstring& processName);

int main()
{
   std::wstring fifi = L"firefox.exe";
   std::wstring gogo = L"chrome.exe";
   auto fifi_proc_id = FindProcessId(fifi);
   auto gogo_proc_id = FindProcessId(gogo);

   if(fifi_proc_id && gogo_proc_id) {
       // both runnin O.O what now?
   }
   else if(fifi_proc_id) {
       // firefox running ... do stuff
   }
   else if(gogo_proc_id) {
       // chrome running ... do stuff
   }
   else {
       // none of both :(
   }
}

And after getting the process ID, how do I make my program understand that it needs to focus on said ID?

对不起,我不知道你说的"make my program understand that it needs to focus on said ID"是什么意思。