Поделиться через


Console.CancelKeyPress Событие

Определение

Происходит при одновременном Control нажатии клавиши модификатора (CTRL) и клавиши консоли (C) или C клавиши прерывания (CTRL+C или CTRL+Break).

public:
 static event ConsoleCancelEventHandler ^ CancelKeyPress;
[System.Runtime.Versioning.UnsupportedOSPlatform("android")]
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
[System.Runtime.Versioning.UnsupportedOSPlatform("ios")]
[System.Runtime.Versioning.UnsupportedOSPlatform("tvos")]
public static event ConsoleCancelEventHandler? CancelKeyPress;
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public static event ConsoleCancelEventHandler? CancelKeyPress;
public static event ConsoleCancelEventHandler CancelKeyPress;
[<System.Runtime.Versioning.UnsupportedOSPlatform("android")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("ios")>]
[<System.Runtime.Versioning.UnsupportedOSPlatform("tvos")>]
member this.CancelKeyPress : ConsoleCancelEventHandler 
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
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 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.ConsoleCancelEventHandler и System.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 не завершит работу приложения.

Обработчик событий для этого события выполняется в потоке пула потоков.

Применяется к

См. также раздел