• C#控制台程序中处理2个关闭事件的代码实例


    我们开发的控制台应用,在运行阶段很有可能被用户Ctrl+C终止或是被用户直接关闭。如果我们不希望用户通过Ctrl+C终止我们的程序,就需要对Ctrl+C或关闭事件作处理。

    处理方法

    在.net平台下Console类有个CancelKeyPress事件可以处理Ctrl+C,不过对于直接关闭控制台应用,这种处理就无能为力了。

    不过Windows API中有个SetConsoleCtrlHandler函数可以处理这两种关闭事件。

    C#处理代码如下:

    导入命名空间

    using System.Runtime.InteropServices;

    处理方法

    在.net平台下Console类有个CancelKeyPress事件可以处理Ctrl+C,不过对于直接关闭控制台应用,这种处理就无能为力了。

    不过Windows API中有个SetConsoleCtrlHandler函数可以处理这两种关闭事件。

    C#处理代码如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    static class Program
    {
        public delegate bool ControlCtrlDelegate(int CtrlType);
        [DllImport("kernel32.dll")]
        private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);
        private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);
     
        public static bool HandlerRoutine(int CtrlType)
        {
            switch (CtrlType)
            {
                case 0:
                    Console.WriteLine("0工具被强制关闭"); //Ctrl+C关闭
                    break;
                case 2:
                    Console.WriteLine("2工具被强制关闭");//按控制台关闭按钮关闭
                    break;
            }
            Console.ReadLine();
            return false;
        }
     
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            SetConsoleCtrlHandler(cancelHandler, true);
            Console.ReadLine();
        }
    }
  • 相关阅读:
    类和对象系列教材 (十二)- 怎么写一个Java的饿汉式与懒汉式单例模式
    类和对象系列教材 (十二)- 怎么写一个Java的饿汉式与懒汉式单例模式
    [LeetCode] 285. Inorder Successor in BST
    [LeetCode] 671. Second Minimum Node In a Binary Tree
    [LeetCode] 230. Kth Smallest Element in a BST
    [LeetCode] 238. Product of Array Except Self
    [LeetCode] 273. Integer to English Words
    [LeetCode] 266. Palindrome Permutation
    [LeetCode] 409. Longest Palindrome
    [LeetCode] 124. Binary Tree Maximum Path Sum
  • 原文地址:https://www.cnblogs.com/lidj/p/6840053.html
Copyright © 2020-2023  润新知