无法在C#控制台应用程序中捕获Ctrl+C
-
13-11-2019 - |
题
我有下面的代码,我试图用它来捕获控制台应用程序中的Ctrl+C:
/// <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;
}
我已经查过了 这里 和 这里, ,但由于某种原因,当我按下Control+C时,Visual Studio2010不会在调试器中进入我的处理程序,我只是得到一个'源代码不可用'屏幕,并有机会继续调试,就是这样。有人知道我为什么不进入处理程序吗?我肯定我只是错过了一些简单的东西。
其他提示
下面的代码对我来说非常适合
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;
}
}
}
.
希望这有帮助!
当Main退出时,您注册的事件处理程序 Console.CancelKeyPress += program.OnCancelKeyPress
收集垃圾。然后,当操作系统尝试访问委托时,没有要运行的代码。
您必须声明要在以下范围之外运行的静态委托 Main
然后在里面分配 Main
这样当操作系统尝试回调它时,它就会停留在作用域中。
不隶属于 StackOverflow