Could not catch Ctrl + C in C # console application

I have the following code that I am trying to use to capture Ctrl + C in a console application:

/// <summary> /// A driver program for testing /// </summary> /// <param name="args">Arguments to the program</param> static void Main(string[] args) { var program = new Program(); Console.Clear(); Console.TreatControlCAsInput = false; Console.CancelKeyPress += program.OnCancelKeyPress; program.Run(args.FirstOrDefault() ?? "3.26.200.125"); Console.WriteLine("Press any key to continue ..."); Console.ReadKey(); } /// <summary> /// Called when [cancel key press]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.ConsoleCancelEventArgs"/> instance containing the event data.</param> internal void OnCancelKeyPress(object sender, ConsoleCancelEventArgs e) { this.Continue = false; e.Cancel = true; } 

I already checked the questions here and here , but for some reason, when I press Control + C, Visual Studio 2010 will not get into my handler in the debugger, I just get the "inaccessible source code" screen and the ability to continue debugging and what it is. Does anyone know why I didn't hit the handler? I'm sure I just missed something simple.

+4
source share
3 answers

Apparently, there is an error from the Connect page:

In the meantime, to work around this problem, you can enable debugging in mixed mode. Then, when you press Ctrl-C, a dialog box appears informing you of the first case of Ctrl-C exception, click Continue. Then you must click the breakpoint in your handler.

+4
source

The code below works fine for me

 using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.Clear(); Console.WriteLine("Press X to quit"); Console.TreatControlCAsInput = false; Console.CancelKeyPress += (s, ev) => { Console.WriteLine("Ctrl+C pressed"); ev.Cancel = true; }; while (true) if (Console.ReadKey().Key == ConsoleKey.X) break; } } } 

Hope this helps!

+1
source

When Main exits, the event handler that you registered with Console.CancelKeyPress += program.OnCancelKeyPress gets garbage collection. Then, when the OS tries to access the delegate, there is no code to run.

You must declare a static delegate that will run outside the Main scope, and then assign it to Main so that it remains in scope when the OS tries to call him back.

0
source

Source: https://habr.com/ru/post/1398714/


All Articles