如何获取特定子进程的进程ID? C ++

问题描述

我想获取特定子进程的进程ID(最终向其写入内存)。这是我当前的代码

#include <Windows.h>
#include <iostream>
#include <TlHelp32.h>
#include <string>
#include <tchar.h>
#include <stdio.h>
#include <psapi.h>

using namespace std;

int main(void)
{
    DWORD ProcessID;

    HWND hwnd = FindWindowA(NULL,"AJ Classic");
    if (hwnd == NULL) {
        cout << "Can't find Process." << endl;
        Sleep(3000);
        exit(-1);
    }
    else {
        GetwindowThreadProcessId(hwnd,&ProcessID);
        HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS,FALSE,ProcessID);

        if (ProcessID == NULL) {
            cout << "Can't optain process" << endl;
            Sleep(3000);
            exit(-1);
        }
        else {
            cout << "Process ID: " << ProcessID << " | Hex: " << hex << ProcessID << dec << endl;
        }
    }
    getchar();
}

在进行实际的内存写入之前,我想确保获得正确的进程ID。 我当前在运行代码时获得的进程ID并非来自我想要其proc ID的子进程。 该屏幕快照代表了我正在尝试获取的进程ID的进程:

enter image description here

我的代码获取ID 8120,但是我希望它获取14244进程。 该怎么办?

解决方法

如果有多个具有给定名称的顶级窗口,则应使用 EnumWindows,然后在您的EnumWindowsProc中检查您是否需要该窗口;如果是,请继续GetWindowThreadProcessId

基于注释,这与窗口无关。因此,您应该使用EnumProcesses来完成所有过程,而不是寻找窗口FindWindowA。但是,“倒数第二个”不是一个很好的ID。它显然取决于排序顺序。您是否知道如何确定目标流程的其他信息?