gpt4 book ai didi

c++ - 从 PID 中检索进程运行目录

转载 作者:行者123 更新时间:2023-11-28 04:35:54 25 4
gpt4 key购买 nike

尝试使用 PID 检索进程的运行目录。我正在使用 FindWindow()GetWindowThreadProcessId() 获取 PID,这导致与任务管理器中显示的进程 ID 相同,因此我认为它是正确的。

当使用 GetModuleFileNameEx() 时,我得到的不是路径,而是内存地址。

auto wnd = FindWindow(nullptr, L"prog");
while (wnd == nullptr)
{
wnd = FindWindow(nullptr, L"prog");
}

TCHAR fBuf[MAX_PATH]; // buffer for path
DWORD procId; // process id
GetWindowThreadProcessId(wnd, &procId); // get process id
std::cout << procId << std::endl; // results in correct pid
auto procHdl = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, procId); // create handle for process
if (procHdl != NULL) {
if (GetModuleFileNameEx(procHdl, 0, fBuf, MAX_PATH) == 0) {
std::cerr << "Failed to get module filename." << std::endl;
}
else {
std::cout << "Module filename is: " << fBuf << std::endl;
}

CloseHandle(procHdl);
}

示例输出是:

10488
Module filename is: 008CF93C

我也使用 GetProcessImageFileNname() 得到了同样的结果。

最佳答案

要获取程序的目录,首先使用 GetModuleFileNameEx 获取程序路径,您的目录将从找到的第一个字符到最后一个反斜杠开始。

例子:

程序是:“C:\Windows\notepad.exe”;
目录是:"C:\Windows";

在代码中:

DWORD pid = 104;
CHAR ProgramFile[MAX_PATH];
std::string DirectoryPath;
HANDLE hProcess = OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_INFORMATION, FALSE, pid);
GetModuleFileNameExA(hProcess, NULL, ProgramFile, MAX_PATH);
DirectoryPath = ProgramFile;
DirectoryPath = DirectoryPath.substr(0, DirectoryPath.find_last_of('\\'));
std::cout << "ProgramFile: " << ProgramFile << endl;
std::cout << "Directory: " << DirectoryPath.c_str();

关于c++ - 从 PID 中检索进程运行目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51453553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com