c#控制台程序 任何时候按Exc就退出

作者&投稿:鲍邹 (若有异议请与网页底部的电邮联系)

默认有Ctrl+C可以中断程序的;

Esc的话,简单的办法就是,用线程;

using System.Threading;


        private static void DetectEsc()
        {
            ConsoleKey exitKey = new ConsoleKey();
            exitKey = Console.ReadKey().Key;
            if (exitKey == ConsoleKey.Escape)
            {
                Console.WriteLine("ESC");
                Environment.Exit(0);
            }
        }

        static void Main(string[] args)
        {
            Thread trd = new Thread(new ThreadStart(DetectEsc));
            trd.Start();

            int i=1;
            while (true)
            {
                Console.WriteLine(i++.ToString());
                Thread.Sleep(2000);
            }
        }


C语言写控制台程序,如何禁止控制台的关闭按钮~

要拦截消息的话可以通过SetConsoleCtrlHandler和HandlerRoutine函数(msdn一下),下面是简单例子:
#include
#include

BOOL MyHandler( DWORD dwCtrlType )
{
if ( dwCtrlType == CTRL_CLOSE_EVENT )
{
printf("Cannot close...
");
return TRUE;
}

return FALSE;
}

void main()
{
SetConsoleCtrlHandler((PHANDLER_ROUTINE)MyHandler, TRUE);

printf("Please try to clsoe...
");
while(1) {};
}


要禁止关闭按钮的话可以直接从系统菜单里移除,比如:
#define _WIN32_WINNT 0x0500
#include
#include

void main()
{
DeleteMenu(GetSystemMenu(GetConsoleWindow(), FALSE), SC_CLOSE, MF_BYCOMMAND);
DrawMenuBar(GetConsoleWindow());

printf("Now you cannot close this window...
");
system("pause");
}

exit(0);