Console.CancelKeyPress Evento
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
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
Tipo de evento
- Atributos
Exemplos
O exemplo a seguir demonstra como o CancelKeyPress evento é usado. Quando você pressiona Ctrl+C, a operação de leitura é interrompida e o myHandler
manipulador de eventos é invocado. Após a entrada para o manipulador de eventos, a propriedade é false
, o ConsoleCancelEventArgs.Cancel que significa que o processo atual será encerrado quando o manipulador de eventos for encerrado. No entanto, o manipulador de eventos define a ConsoleCancelEventArgs.Cancel propriedade como true
, o que significa que o processo não será encerrado e a operação de leitura será retomada.
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
Comentários
Esse evento é usado em conjunto com System.ConsoleCancelEventHandler e System.ConsoleCancelEventArgs. O CancelKeyPress evento permite que um aplicativo de console intercepte o sinal Ctrl+C para que o manipulador de eventos possa decidir se deseja continuar executando ou encerrando. Para obter mais informações sobre como lidar com eventos, consulte Manipulando e levantando eventos.
Quando o usuário pressiona Ctrl+C ou Ctrl+Break, o CancelKeyPress evento é acionado e o manipulador de eventos do ConsoleCancelEventHandler aplicativo é executado. O manipulador de eventos é passado por um ConsoleCancelEventArgs objeto que tem duas propriedades úteis:
SpecialKey, que permite determinar se o manipulador foi invocado como resultado do usuário pressionando Ctrl+C (o valor da propriedade é ConsoleSpecialKey.ControlC) ou Ctrl+Break (o valor da propriedade é ConsoleSpecialKey.ControlBreak).
Cancel, que permite determinar como seu aplicativo deve responder ao usuário pressionando Ctrl+C ou Ctrl+Break. Por padrão, a Cancel propriedade é
false
, que faz com que a execução do programa seja encerrada quando o manipulador de eventos for encerrado. Alterar sua propriedade paratrue
especifica que o aplicativo deve continuar a ser executado.
Dica
Se o aplicativo tiver requisitos simples, você poderá usar a TreatControlCAsInput propriedade em vez desse evento. Definindo essa propriedade como false
, você pode garantir que seu aplicativo sempre saia se o usuário pressionar Ctrl+C. Ao defini-lo como true
, você pode garantir que pressionar Ctrl+C não encerrará o aplicativo.
O manipulador de eventos para esse evento é executado em um thread de pool de threads.