gpt4 book ai didi

c# - 为什么关闭使用 AllocConsole 启动的控制台会导致我的整个应用程序退出?我可以改变这种行为吗?

转载 作者:IT王子 更新时间:2023-10-29 04:15:47 26 4
gpt4 key购买 nike

我想要发生的是控制台窗口消失,或者更好的是它被隐藏,但我希望我的应用程序继续运行。那可能吗?我希望能够使用 Console.WriteLine 并将控制台用作输出窗口。我希望能够隐藏和显示它,我不希望整个应用程序仅仅因为控制台关闭而死掉。

编辑

代码:

internal class SomeClass {

[DllImport("kernel32")]
private static extern bool AllocConsole();

private static void Main() {
AllocConsole();
while(true) continue;
}
}

编辑 2

我在这里尝试了公认的解决方案 [ Capture console exit C# ],根据对这个问题的评论中的建议。示例代码存在错误,因为 DLLImport 需要是“kernel32.dll”或“kernel32”,而不是“Kernel32”。进行该更改后,当我单击控制台窗口上的 X 时,我的处理程序将收到一条 CTRL_CLOSE_EVENT 消息。但是,调用 FreeConsole 和/或返回 true 不会阻止应用程序终止。

最佳答案

啊,是的,这是使用 Windows 控制台子系统的警告之一。当用户关闭控制台窗口时(无论控制台是如何分配的),连接到控制台的所有进程都将终止。这种行为对于控制台应用程序(即那些专门针对控制台子系统的应用程序,而不是标准的 Windows 应用程序)来说显然是有意义的,但在像您这样的情况下,这可能是一个主要的痛苦。

我所知道的唯一解决方法是使用 SetConsoleCtrlHandler function ,它允许您为 Ctrl+CCtrl+Break 信号注册处理函数,以及系统事件,例如用户关闭控制台窗口、用户注销或系统关闭。文档说如果您只想忽略这些事件,您可以为第一个参数传递 null。例如:

[DllImport("kernel32")]
static extern bool SetConsoleCtrlHandler(HandlerRoutine HandlerRoutine, bool Add);

delegate bool HandlerRoutine(uint dwControlType);

static void Main()
{
AllocConsole();
SetConsoleCtrlHandler(null, true);
while (true) continue;
}

这非常适用于 Ctrl+CCtrl+Break 信号(否则会导致您应用程序也终止),但它不适用于您询问的那个,即用户关闭控制台窗口时系统生成的 CTRL_CLOSE_EVENT

老实说,我不知道如何防止这种情况发生。连the sample in the SDK实际上不允许您忽略 CTRL_CLOSE_EVENT。我在一个小测试应用程序中尝试过,当您关闭窗口并打印消息时它发出哔哔声,但进程仍然终止。

也许更令人担忧的是,文档让我认为无法阻止这种情况:

The system generates CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT signals when the user closes the console, logs off, or shuts down the system so that the process has an opportunity to clean up before termination. Console functions, or any C run-time functions that call console functions, may not work reliably during processing of any of the three signals mentioned previously. The reason is that some or all of the internal console cleanup routines may have been called before executing the process signal handler.

吸引我眼球的是最后一句话。如果控制台子系统在响应用户试图关闭窗口后立即开始清理,则可能无法在事后停止它。

(至少现在你明白了问题所在。也许其他人可以提出解决方案!)

关于c# - 为什么关闭使用 AllocConsole 启动的控制台会导致我的整个应用程序退出?我可以改变这种行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11959643/

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