Hello. Tell me, how can I catch the event of clicking on the cross in the console application?

  • Very strange question. And if there is no cross? - alexlz
  • All applications have it ... At the top right. - Csharp
  • 2
    and have a console? Sorry for munusovat until I can not: ( - e_klimin
  • 3
    The question is incorrect. The author, apparently, meant processing the close signal of the console application "from the outside" (be it a "cross", if the console is running in a windowed environment, or something else). Formulate the question correctly, there are no telepaths here :) - Shad
  • What type of HandleConsoleError; where and how to declare it - user11234

2 answers 2

The System.Console class has the CancelKeyPress event, but it only works for the Ctrl + C and Ctrl + Break shortcuts - the standard hotkeys for closing a console application.

If you want to catch all the signals to close the application (closing the console window, logging off the user, or shutting down the system), you can use the SetConsoleCtrlHandler WinAPI function, after importing it from kernel32.dll. You will also need to describe several constants, a description of which can be found on this page , and a delegate for your callback method.

internal delegate void SignalHandler(ConsoleSignal consoleSignal); internal enum ConsoleSignal { CtrlC = 0, CtrlBreak = 1, Close = 2, LogOff = 5, Shutdown = 6 } internal static class ConsoleHelper { [DllImport("Kernel32", EntryPoint = "SetConsoleCtrlHandler")] public static extern bool SetSignalHandler(SignalHandler handler, bool add); } 

To close the console window, the consoleSignal parameter will be set to ConsoleSignal.Close . You can use it, for example, like this:

 public sealed class Program { private static SignalHandler signalHandler; public static void Main(string[] args) { signalHandler += HandleConsoleSignal; ConsoleHelper.SetSignalHandler(signalHandler, true); // ... } private static void HandleConsoleSignal(ConsoleSignal consoleSignal) { // TO DO } } 

From my own experience I will say that only a few seconds are allocated for processing such a signal, so you should not perform unnecessary actions in the handler.

  • one
    What type of HandleConsoleError; How and where to define it? - user11234
  • Instead, it should be HandleConsoleSignal. Thanks for the comment, corrected the answer. - Shad

Most likely you need to handle Environment.Exit or Application.Exit .

The console application does not have a cross, which is why it is a console. If you run the application in the console, then the cross is at the console itself, and not at your application.