当按下Escape键时退出控制台应用程序

本文关键字:退出 控制台 应用程序 Escape | 更新日期: 2023-09-27 18:08:59

请任何人帮助我,我想定制我的控制台程序,只有当用户按下键盘上的Escape键时才退出。谢谢你的帮助。c#控制台应用程序

当按下Escape键时退出控制台应用程序

试试下面这个

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication
{
         [DllImport("user32.dll")]
        static extern bool EnableMenuItem(IntPtr hMenu, uint uIDEnableItem, uint uEnable);
        [DllImport("user32.dll")]
        static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
        internal const UInt32 SC_CLOSE = 0xF060;
        internal const UInt32 MF_ENABLED = 0x00000000;
        internal const UInt32 MF_GRAYED = 0x00000001;
        internal const UInt32 MF_DISABLED = 0x00000002;
        internal const uint MF_BYCOMMAND = 0x00000000;

        static void Main(string[] args)
        {
            EnableCloseButton(this, false);
        }
        public static void EnableCloseButton(IWin32Window window, bool bEnabled)
        {
            IntPtr hSystemMenu = GetSystemMenu(window.Handle, false);
            EnableMenuItem(hSystemMenu, SC_CLOSE, (uint)(MF_ENABLED | (bEnabled ? MF_ENABLED : MF_GRAYED)));
        }

    }