Console.CancelKeyPress 事件

定义

Control 修改键 (Ctrl) 和 C console 键 (C) 或 Break 键同时按住(Ctrl+C 或 Ctrl+Break)时发生。

public:
 static event ConsoleCancelEventHandler ^ CancelKeyPress;
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static event ConsoleCancelEventHandler? CancelKeyPress;
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public static event ConsoleCancelEventHandler? CancelKeyPress;
public static event ConsoleCancelEventHandler CancelKeyPress;
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
member this.CancelKeyPress : ConsoleCancelEventHandler 
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("android")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
member this.CancelKeyPress : ConsoleCancelEventHandler 
member this.CancelKeyPress : ConsoleCancelEventHandler 
Public Shared Custom Event CancelKeyPress As ConsoleCancelEventHandler 

事件类型

属性

示例

以下示例演示如何 CancelKeyPress 使用 事件。 按 Ctrl+C 时,读取操作将中断并 myHandler 调用事件处理程序。 进入事件处理程序时, ConsoleCancelEventArgs.Cancel 属性为 false,这意味着当事件处理程序终止时,当前进程将终止。 但是,事件处理程序将 ConsoleCancelEventArgs.Cancel 属性设置为 true,这意味着进程不会终止,读取操作将恢复。

using namespace System;

void OnCancelKeyPressed(Object^ sender, 
    ConsoleCancelEventArgs^ args)
{
    Console::WriteLine("{0}The read operation has been interrupted.",
        Environment::NewLine);

    Console::WriteLine("  Key pressed: {0}", args->SpecialKey);

    Console::WriteLine("  Cancel property: {0}", args->Cancel);

    // Set the Cancel property to true to prevent the process from 
    // terminating.
    Console::WriteLine("Setting the Cancel property to true...");
    args->Cancel = true;

    // Announce the new value of the Cancel property.
    Console::WriteLine("  Cancel property: {0}", args->Cancel);
    Console::WriteLine("The read operation will resume...{0}",
        Environment::NewLine);
}

int main()
{       
    // Clear the screen.
    Console::Clear();

    // Establish an event handler to process key press events.
    Console::CancelKeyPress += 
        gcnew ConsoleCancelEventHandler(OnCancelKeyPressed);

    while (true)
    {
        // Prompt the user.
        Console::Write("Press any key, or 'X' to quit, or ");
        Console::WriteLine("CTRL+C to interrupt the read operation:");

        // Start a console read operation. Do not display the input.
        ConsoleKeyInfo^ keyInfo = Console::ReadKey(true);

        // Announce the name of the key that was pressed .
        Console::WriteLine("  Key pressed: {0}{1}", keyInfo->Key, 
            Environment::NewLine);

        // Exit if the user pressed the 'X' key.
        if (keyInfo->Key == ConsoleKey::X)
        {
            break;
        }
    }
}
// The example displays output similar to the following:
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//    Key pressed: J
//    
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//    Key pressed: Enter
//    
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//    
//    The read operation has been interrupted.
//    Key pressed: ControlC
//    Cancel property: False
//    Setting the Cancel property to true...
//    Cancel property: True
//    The read operation will resume...
//    
//    Key pressed: Q
//    
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//    Key pressed: X
using System;

class Sample
{
    public static void Main()
    {
        ConsoleKeyInfo cki;

        Console.Clear();

        // Establish an event handler to process key press events.
        Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler);
        while (true)
        {
            Console.Write("Press any key, or 'X' to quit, or ");
            Console.WriteLine("CTRL+C to interrupt the read operation:");

            // Start a console read operation. Do not display the input.
            cki = Console.ReadKey(true);

            // Announce the name of the key that was pressed .
            Console.WriteLine($"  Key pressed: {cki.Key}\n");

            // Exit if the user pressed the 'X' key.
            if (cki.Key == ConsoleKey.X) break;
        }
    }

    protected static void myHandler(object sender, ConsoleCancelEventArgs args)
    {
        Console.WriteLine("\nThe read operation has been interrupted.");

        Console.WriteLine($"  Key pressed: {args.SpecialKey}");

        Console.WriteLine($"  Cancel property: {args.Cancel}");

        // Set the Cancel property to true to prevent the process from terminating.
        Console.WriteLine("Setting the Cancel property to true...");
        args.Cancel = true;

        // Announce the new value of the Cancel property.
        Console.WriteLine($"  Cancel property: {args.Cancel}");
        Console.WriteLine("The read operation will resume...\n");
    }
}
// The example displays output similar to the following:
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//      Key pressed: J
//
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//      Key pressed: Enter
//
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//
//    The read operation has been interrupted.
//      Key pressed: ControlC
//      Cancel property: False
//    Setting the Cancel property to true...
//      Cancel property: True
//    The read operation will resume...
//
//      Key pressed: Q
//
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//      Key pressed: X
open System

let myHandler sender (args: ConsoleCancelEventArgs) =
    printfn "\nThe read operation has been interrupted."

    printfn $"  Key pressed: {args.SpecialKey}"

    printfn $"  Cancel property: {args.Cancel}"

    // Set the Cancel property to true to prevent the process from terminating.
    printfn "Setting the Cancel property to true..."
    args.Cancel <- true

    // Announce the new value of the Cancel property.
    printfn $"  Cancel property: {args.Cancel}"
    printfn "The read operation will resume...\n"

// Establish an event handler to process key press events.
Console.CancelKeyPress.AddHandler(ConsoleCancelEventHandler myHandler)

let mutable quit = false
while not quit do
    printf "Press any key, or 'X' to quit, or "
    printfn "CTRL+C to interrupt the read operation:"

    // Start a console read operation. Do not display the input.
    let cki = Console.ReadKey true

    // Announce the name of the key that was pressed .
    printfn $"  Key pressed: {cki.Key}\n"

    // Exit if the user pressed the 'X' key.
    if cki.Key = ConsoleKey.X then
        quit <- true

// The example displays output similar to the following:
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//      Key pressed: J
//
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//      Key pressed: Enter
//
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//
//    The read operation has been interrupted.
//      Key pressed: ControlC
//      Cancel property: False
//    Setting the Cancel property to true...
//      Cancel property: True
//    The read operation will resume...
//
//      Key pressed: Q
//
//    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
//      Key pressed: X
Class Sample
    Public Shared Sub Main() 
        Dim cki As ConsoleKeyInfo
        
        Console.Clear()
        
        ' Establish an event handler to process key press events.
        AddHandler Console.CancelKeyPress, AddressOf myHandler

        While True
            Console.Write("Press any key, or 'X' to quit, or ")
            Console.WriteLine("CTRL+C to interrupt the read operation:")
            
            ' Start a console read operation. Do not display the input.
            cki = Console.ReadKey(True)
            
            ' Announce the name of the key that was pressed .
            Console.WriteLine($"  Key pressed: {cki.Key}{vbCrLf}")
            
            ' Exit if the user pressed the 'X' key.
            If cki.Key = ConsoleKey.X Then Exit While
        End While
    End Sub

    Protected Shared Sub myHandler(ByVal sender As Object, _
                                   ByVal args As ConsoleCancelEventArgs) 
        Console.WriteLine($"{vbCrLf}The read operation has been interrupted.")
        
        Console.WriteLine($"  Key pressed: {args.SpecialKey}")
        
        Console.WriteLine($"  Cancel property: {args.Cancel}")
        
        ' Set the Cancel property to true to prevent the process from terminating.
        Console.WriteLine("Setting the Cancel property to true...")
        args.Cancel = True
        
        ' Announce the new value of the Cancel property.
        Console.WriteLine($"  Cancel property: {args.Cancel}")
        Console.WriteLine($"The read operation will resume...{vbCrLf}")
    End Sub
End Class
' The example diplays output similar to the following:
'    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
'     Key pressed: J
'    
'    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
'     Key pressed: Enter
'    
'    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
'    
'    The read operation has been interrupted.
'     Key pressed: ControlC
'     Cancel property: False
'    Setting the Cancel property to true...
'     Cancel property: True
'    The read operation will resume...
'    
'     Key pressed: Q
'    
'    Press any key, or 'X' to quit, or CTRL+C to interrupt the read operation:
'     Key pressed: X

注解

此事件与 System.ConsoleCancelEventHandlerSystem.ConsoleCancelEventArgs结合使用。 事件 CancelKeyPress 使控制台应用程序能够截获 Ctrl+C 信号,以便事件处理程序可以决定是继续执行还是终止。 有关处理事件的详细信息,请参阅 处理和引发事件

当用户按 Ctrl+C 或 Ctrl+Break 时, CancelKeyPress 将触发事件并执行应用程序的 ConsoleCancelEventHandler 事件处理程序。 事件处理程序将传递具有两个 ConsoleCancelEventArgs 有用属性的对象:

  • SpecialKey,用于确定处理程序是用户按 Ctrl+C (属性值 ConsoleSpecialKey.ControlC) 还是 ctrl+Break (属性值 ConsoleSpecialKey.ControlBreak) 调用。

  • Cancel,这样就可以确定应用程序应如何响应按 Ctrl+C 或 Ctrl+Break 的用户。 默认情况下, Cancel 属性为 false,这会导致当事件处理程序退出时程序执行终止。 将其属性更改为 true 指定应用程序应继续执行。

提示

如果应用程序有简单的要求,则可以使用 TreatControlCAsInput 属性而不是此事件。 通过将此属性设置为 false,可以确保在用户按 Ctrl+C 时,应用程序始终退出。 通过将它设置为 true,可以确保按 Ctrl+C 不会终止应用程序。

此事件的事件处理程序在线程池线程上执行。

适用于

另请参阅