C# 控制台程序屏蔽关闭按钮,关闭快速编辑模式,注册关闭事件
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleCloseTest
{
internal class Program
{
//激活关闭窗口事件
public delegate bool ControlCtrlDelegate(int CtrlType);
[DllImport("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerAppClose, bool Add);
private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerAppClose);
//取消控制台关闭按钮
private const int MF_BYCOMMAND = 0x00000000;
public const int SC_CLOSE = 0xF060;
[DllImport("user32.dll")]
public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);
[DllImport("user32.dll")]
public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GetConsoleWindow();
//关闭控制台快速编辑模式
const int STD_INPUT_HANDLE = -10;
const uint ENABLE_QUICK_EDIT_MODE = 0x0040;
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetStdHandle(int hConsoleHandle);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint mode);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint mode);
static void Main(string[] args)
{
//注册窗口关闭事件
bool bRet = SetConsoleCtrlHandler(cancelHandler, true);
//禁用关闭按钮
IntPtr consoleWindow = GetConsoleWindow();
IntPtr sysMenu = GetSystemMenu(consoleWindow, false);
if (consoleWindow != IntPtr.Zero) DeleteMenu(sysMenu, SC_CLOSE, MF_BYCOMMAND);
//关闭控制台快速编辑模式
DisableQuickEditMode();
Console.WriteLine("Func Main Called");
Console.WriteLine("Enter 'exit' to exit the program ...");
while (true)
{
Thread.Sleep(1);
string s = Console.ReadLine();//一次输入一行
if (s.ToUpper() == "EXIT") break;
}
}
/// <summary>
/// 打开快速编辑模式
/// </summary>
public static void EnableQuickEditMode()
{
IntPtr hStdin = GetStdHandle(STD_INPUT_HANDLE);
uint mode;
GetConsoleMode(hStdin, out mode);
mode |= ENABLE_QUICK_EDIT_MODE;
SetConsoleMode(hStdin, mode);
}
/// <summary>
/// 关闭快速编辑模式
/// </summary>
public static void DisableQuickEditMode()
{
IntPtr hStdin = GetStdHandle(STD_INPUT_HANDLE);
uint mode;
GetConsoleMode(hStdin, out mode);
mode &= ~ENABLE_QUICK_EDIT_MODE;
SetConsoleMode(hStdin, mode);
}
/// <summary>
/// 关闭窗口时的事件
/// </summary>
/// <param name="CtrlType"></param>
/// <returns></returns>
static bool HandlerAppClose(int CtrlType)
{
Console.WriteLine("关闭窗口事件被激活");
Console.WriteLine("do something...");
Thread.Sleep(5000);
Environment.Exit(0);
return false;
}
}
}