How to add window close event to C# console application?

The company has a console application and wants to process the business logic before closing the console application window. For example, if it is closed by mistake, or if the message queue starts sending message reminders, then closing the window means that the console application is destroyed, and message notifications also need to be sent. Then adding the close window event will come in handy at this time.

Many friends ask, is there a way to control the form closing and exit events like WinForm? There is none by default, we can write it ourselves. Follow these steps:

1. Write the following code in the Program class of the [Program.cs] file. Adding a delegate HandlerAppClose is to pass the function pointer to the system API function SetConsoleCtrlHandler.

Code:

        #region 激活关闭窗口事件
        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);

        /// <summary>
        /// 关闭窗口时的事件
        /// </summary>
        /// <param name="CtrlType"></param>
        /// <returns></returns>
        static bool HandlerAppClose(int CtrlType)
        {
            Console.WriteLine("关闭窗口事件被激活");
            Console.WriteLine("do something...");
            return false;
        }

        #endregion

2. Then register the window closing event in the Main method of the Program class.

Code:

//注册窗口关闭事件
bool bRet = SetConsoleCtrlHandler(cancelHandler, true);

3. The effect is as follows. When you click [x] to close the window, the window close event will be triggered.

Will enter this event:

Copyright statement: This article is an original article, and the copyright belongs to [Xigua Programmer]. Please indicate the source when reprinting. If you have any questions, please send a private message.

Original link:How to add a window closing event to a C# console application? _Xigua Programmer’s Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/2301_79251107/article/details/132174074