禁用control + c关闭程序

R.V*_*tor 1 c# methods key break

我有一个循环ping请求的方法,我想当我点击Ctrl+时c,它会打破循环并给我像普通cmd一样的静态,但当我点击Ctrl+时c,我得到

按任意键继续... <<

然后程序关闭.

例如:ping google.com -t <<将以无限循环ping谷歌,但我需要在点击Ctrl+ 时才打破循环c

private void _t(string website)
{
    Ping pingSender = new Ping();
    string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    byte[] buffer = Encoding.ASCII.GetBytes(data);
    int timeout = 10000;
    try
    {
        PingOptions options = new PingOptions(64, false);
        PingReply send0 = pingSender.Send(website, timeout, buffer, options);
        Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
        while (1 < 2)
        {
            PingReply reply = pingSender.Send(website, timeout, buffer, options);

            if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime / 5, reply.Options.Ttl);
            }
            else
            {
                Console.WriteLine("Request timed out.");
            }
        }
    }
    catch
    {
        Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
    }
}
Run Code Online (Sandbox Code Playgroud)

但不是使用while (1<2),我想使用类似的东西:

while (ConsoleKeyInfo.Equals("Control + c") not clicked) // sure it is wrong , but that`s what I wanna achieve
{
    PingReply reply = pingSender.Send(website, timeout, buffer, options);

    if (reply.Status == IPStatus.Success)
    {
        Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}",        reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime / 5, reply.Options.Ttl);
    }
    else
    {
        Console.WriteLine("Request timed out.");
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 6

我可能会有点迟到,但这是一个更好的方式,适用于所有平台:

Console.TreatControlCAsInput = true;
Run Code Online (Sandbox Code Playgroud)