如何在不显示 Win32 GUI 程序的控制台窗口的情况下执行子控制台程序?

2022-01-12 00:00:00 windows c c++ console-application mfc

(我搜索了 SO 答案,但没有找到明确的解决方案.)

(I've searched SO answers and found no clear solution to this problem.)

我正在开发 MFC GUI 程序.该程序运行各种子程序,包括控制台程序和shell命令脚本(.cmd).

I'm working on a MFC GUI program. This program runs various child programs including console program and shell command script(.cmd).

最初它显示一个 GUI 窗口和一个控制台窗口(使用 AllocConsole 创建),因为子进程有很多控制台输出.但是很多用户抱怨控制台窗口,所以我们决定隐藏控制台窗口.

Initially it displayed one GUI window and one console window (created with AllocConsole) because there are many console output from the child processes. But many users complained about the console window so we decided to hide the console window.

首先尝试如下:

if (AllocConsole())
{
    ::ShowWindow(::GetConsoleWindow(), SW_HIDE);
}

好的,没有控制台窗口,但在控制台创建时有可见的闪烁.我已经尝试了几个 CreateProcess 选项来创建子进程,以完全阻止控制台窗口的显示,但总之失败了,我认为这实际上是不可能的.

Okay, no console window but there are visible flicker at the console creation time. I've tried several CreateProcess options for child process creation to prevent showing of console window altogether but failed at short and I think it is practically impossible.

这没什么大不了的.我们可以忽略启动时的临时窗口闪烁.

It is not a big deal. We can ignore temporary window flicker at the startup.

但是真的不能完全隐藏子控制台窗口吗?

But is it really impossible to hide child console window completely?

推荐答案

像这样为 CreateProcess 调用设置 STARTUPINFO:

Setup the STARTUPINFO like this for the CreateProcess call:

    STARTUPINFO si = { 0 };
    si.cb = sizeof(si);
    si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
    si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
    si.hStdOutput =  GetStdHandle(STD_OUTPUT_HANDLE);
    si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
    si.wShowWindow = SW_HIDE;

相关文章