关闭控制台而无需终止进程 [英] Closing Console without killing Process

查看:67
本文介绍了关闭控制台而无需终止进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,
尽管我们可以在网上找到几个有关我的问题的答案,但我无法找到满足我需求的完整答案,这就是为什么我在这里发布.

在Windows应用程序中,我使用AllocConsole打开连接的控制台.
一旦我想关闭控制台(单击右上角的"x"或Alt-F4),一切都将关闭.已关闭,包括正在调用的Windows应用程序.

为了运行FreeConsole,我确实尝试使用SetConsoleCtrlHandler截取关闭信号.它可以与Ctrl-C或Ctrl-Break一起使用.但是单击'x'会使控制台挂起5秒钟(此信号超时),最后一切都关闭了.

一种可接受的解决方法是停用'x':
DeleteMenu(GetSystemMenu(GetConsoleWindow (),0),0xF060,0);
我在这里发布是因为我想在您的帮助下进一步向前发展.

实际上,我们应该在ExitProcess运行之前中断.
在某些情况下,将打开窗口程序结束",并提供等待或退出应用程序的权限.在这种情况下,选择``等待''只会关闭控制台.
有没有一种方法可以通过编程方式模拟这种行为? (如果没有打开最后一个窗口,是否有可能)?

解决方案

您好,eTill,

我试图实现您在您的描述中描述的功能 张贴在上面,我就和您遇到的一样完全解决了这个问题.

当我尝试通过单击"X"关闭控制台窗口时 右上角标题栏上的按钮,它被卡了大约5秒钟,有时 它弹出一个结束程序"对话框(处于调试状态),我尝试对其进行调试, 发现5秒钟花在

私有 静态 bool ConsoleCtrlCheck( CtrlTypes ctrlType)

//在此处放置您自己的处理程序

开关(ctrlType)

保护套 CtrlTypes .CTRL_C_EVENT:

控制台 .WriteLine("收到CTRL + C !" );

break ;

保护套 CtrlTypes .CTRL_BREAK_EVENT:

控制台 .WriteLine("收到CTRL + BREAK !" );

break ;

保护套 CtrlTypes .CTRL_CLOSE_EVENT:

控制台 .WriteLine("程序正在关闭! " );

//< --------检查 此代码段将有效

break ;

保护套 CtrlTypes .CTRL_LOGOFF_EVENT:

保护套 CtrlTypes .CTRL_SHUTDOWN_EVENT:

控制台 .WriteLine("用户正在注销!" );

break ;

返回 true ;

解决方案

Hi eTill,

I tried to implement the function as you described in your post above, and I got the problem as exactly as you got.

When I tried to close the console window by clicking the "X" button on right-top title bar, it was stuck for about 5 seconds, and sometimes it popup an "End program" dialog (in the debug state), I tried to debug it, I found the 5 seconds was spent  on unknown code.

However, when I tried to "return false" before run "FreeConsole()", the console was closed immediately, please check the code snippet below.

private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)

        {

            // Put your own handler here

            switch (ctrlType)

            {

                case CtrlTypes.CTRL_C_EVENT:

                    Console.WriteLine("CTRL+C received!");

                    FreeConsole();

                    break;

 

                case CtrlTypes.CTRL_BREAK_EVENT:

                    Console.WriteLine("CTRL+BREAK received!");

                    FreeConsole();

                    break;

 

                case CtrlTypes.CTRL_CLOSE_EVENT:

                    Console.WriteLine("Program being closed!");

                       return false; //<-------- check this code snippet will work

                    FreeConsole();

                    break;

 

                case CtrlTypes.CTRL_LOGOFF_EVENT:

                case CtrlTypes.CTRL_SHUTDOWN_EVENT:

                    Console.WriteLine("User is logging off!");

                    FreeConsole();

                   

                    break;

 

            }

            return true;

        }

Regards,

Xun


这篇关于关闭控制台而无需终止进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆