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

时间:2015-08-21 07:41:47

标签: c#

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

1 个答案:

答案 0 :(得分:2)

尝试像这样的人

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)));
        }


    }

Source