4

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.

4

3 回答 3

4

显然,连接页面有一个解决方法是:

同时,要解决此问题,您可以启用混合模式调试。然后,当您按下 Ctrl-C 并弹出一个对话框,通知您第一次出现 Ctrl-C 异常时,单击“继续”。然后,您应该在处理程序中点击断点。

于 2012-02-27T23:19:05.520 回答
1

下面的代码对我很有用

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;
        }
    }
}

希望这可以帮助!

于 2012-02-27T23:27:42.320 回答
0

当 Main 退出时,您注册的事件处理程序会Console.CancelKeyPress += program.OnCancelKeyPress被垃圾收集。然后,当操作系统尝试访问委托时,没有要运行的代码。

您必须声明一个静态委托在范围之外运行Main,然后在其中分配它,Main以便当操作系统尝试回调它时它保持在范围内。

于 2012-02-28T00:07:39.267 回答