gpt4 book ai didi

c++ - 防止子进程的控制台强制关闭

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

我正在从我的主流程创建 5 个子流程并等待它们全部完成。每个子进程都创建自己的控制台窗口。我想要做的是禁用子进程创建的控制台窗口的关闭按钮。我找不到任何资源来做到这一点。

  • 如何使子进程的控制台保持打开状态,以便在用户按下控制台的关闭按钮时它不会关闭?
  • GetExitCodeProcess(pi.hProcess, &exitCode) 总是返回 false & 来自 GetLastError() 的最后一个错误代码是 5。但是 exitCode 的值code> 显示正确的值。为什么会这样?

这是我的代码:

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <string>
#include <iostream>
#include <vector>
using namespace std;

wstring to_wstring(const string& str)
{
std::wstring ws;
ws.assign(str.begin(), str.end());
return ws;
}

vector<PROCESS_INFORMATION> v;

int main(int argc, TCHAR *argv[])
{
int noOfProcess = 4;
for (int i = 1; i <= noOfProcess; i++) {
STARTUPINFO si;
PROCESS_INFORMATION pi;

ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

auto ws = to_wstring("D:\\programming\\test.exe");
TCHAR *cmd;
cmd = new TCHAR[ws.length() + 10];
_tcscpy_s(cmd, ws.length() + 1, ws.c_str());

// Start the child process.
if (!CreateProcess(NULL, // No module name (use command line)
cmd, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
true, // Set handle inheritance to FALSE
CREATE_NEW_CONSOLE, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
return 0;
}

cout << "Started Process " << pi.hProcess << endl;
v.push_back(pi);
}
while (v.size()) {
for (auto it = v.begin(), next_it = v.begin(); it != v.end(); it = next_it) {
next_it = it; it++;
PROCESS_INFORMATION &pi = *it;
DWORD exitCode = 0;
if (GetExitCodeProcess(pi.hProcess, &exitCode) == FALSE)
{
// Always return error code 5 but exitcode is set to correct value
cout << GetLastError() << endl;
}
if (exitCode == STILL_ACTIVE)
continue;
cout << "Finished Process " << pi.hProcess << " With exit code " << exitCode << endl;
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
v.erase(it);
}
}
return 0;
}

最佳答案

  1. 尝试通过这种方式禁用子进程中的关闭按钮(您要禁用关闭按钮的时刻)。

    DeleteMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE, MF_BYCOMMAND);

  2. 根据 MSDN 文档 here , GetExitCodeProcess() 的句柄必须具有 PROCESS_QUERY_INFORMATION 访问权限。使用 PROCESS_QUERY_INFORMATION 打开进程。

    OpenProcess(PROCESS_QUERY_INFORMATION, true, pi.dwProcessId);

  3. 我测试了你的代码,里面有一个错误。当v.size() = 1时,it++会跳出vector,然后*it抛出异常。在 v.erase(it) 之后,你最好 break 并重新启动 for 循环(在 v.erase(it); 之后添加 break;)。

关于c++ - 防止子进程的控制台强制关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53482804/

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