简体   繁体   中英

Unable to trap Ctrl+C in a C# console app

I've got the following code that I'm trying to use to trap Ctrl+C in a console app:

    /// <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've already checked the questions here and here , but for some reason, when I press Control+C, Visual Studio 2010 won't get into my handler in the debugger, I just get a 'source code unavailable' screen, and the opportunity to continue debugging, and that's it. Does anybody have any idea why I'm not getting into the handler ? I'm sure I'm just missing something simple.

Apparently there is a bug a work around from the Connect page is:

In the meantime, to work around this problem, you can enable mixed-mode debugging. Then, when you hit Ctrl-C and a dialog pops up notifying you of the first chance Ctrl-C exception, click "Continue". You should then hit the breakpoint in your handler.

The code below works great 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!

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

You must declare a static delegate to be run outside the scope of Main and then assign it within Main so that it stays in scope when the OS attempts to call back to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM