Console.CancelKeyPress 이벤트

정의

Control 보조 키(Ctrl)와 C 콘솔 키(C) 또는 Break 키를 동시에 누르면(Ctrl+C 또는 Ctrl+Break) 발생합니다.Occurs when the Control modifier key (Ctrl) and either the C console key (C) or the Break key are pressed simultaneously (Ctrl+C or Ctrl+Break).

public:
 static event ConsoleCancelEventHandler ^ CancelKeyPress;
public static event ConsoleCancelEventHandler CancelKeyPress;
member this.CancelKeyPress : ConsoleCancelEventHandler 
Public Shared Custom Event CancelKeyPress As ConsoleCancelEventHandler 

예제

다음 예제에서는 방법을 CancelKeyPress 이벤트가 사용 됩니다.The following example demonstrates how the CancelKeyPress event is used. 읽기 작업이 중단 되는 Ctrl + C를 누르면 및 myHandler 이벤트 처리기가 호출 됩니다.When you press Ctrl+C, the read operation is interrupted and the myHandler event handler is invoked. 이벤트 처리기에 진입할 때 합니다 ConsoleCancelEventArgs.Cancel 속성은 false, 즉, 이벤트 처리기가 종료 될 때 현재 프로세스가 종료 됩니다.Upon entry to the event handler, the ConsoleCancelEventArgs.Cancel property is false, which means that the current process will terminate when the event handler terminates. 그러나 이벤트 처리기를 설정 합니다는 ConsoleCancelEventArgs.Cancel 속성을 true, 프로세스 종료 되지는 것입니다. 읽기 작업은 다시 시작을 의미 합니다.However, the event handler sets the ConsoleCancelEventArgs.Cancel property to true, which means that the process will not terminate and the read operation will resume.

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
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입니다.This event is used in conjunction with System.ConsoleCancelEventHandler and System.ConsoleCancelEventArgs. CancelKeyPress 이벤트에 이벤트 처리기는 계속 실행 또는 종료 여부를 결정할 수 있도록 Ctrl + C 신호를 가로채 콘솔 애플리케이션을 사용 하도록 설정 합니다.The CancelKeyPress event enables a console application to intercept the Ctrl+C signal so the event handler can decide whether to continue executing or terminate. 이벤트 처리에 대한 자세한 내용은 이벤트 처리 및 발생 을 참조하십시오.For more information about handling events, see Handling and Raising Events.

사용자가 Ctrl + Break 또는 Ctrl + C를 누를 때를 CancelKeyPress 이벤트가 발생 하 고 애플리케이션의 ConsoleCancelEventHandler 이벤트 처리기가 실행 됩니다.When the user presses either Ctrl+C or Ctrl+Break, the CancelKeyPress event is fired and the application's ConsoleCancelEventHandler event handler is executed. 이벤트 처리기에 전달 되는 ConsoleCancelEventArgs 두 가지 유용한 속성이 있는 개체:The event handler is passed a ConsoleCancelEventArgs object that has two useful properties:

  • SpecialKeyCtrl + C를 누르면 사용자로 인해 처리기가 호출 여부를 확인할 수 있습니다 (속성 값이 ConsoleSpecialKey.ControlC) 또는 Ctrl + Break (속성 값이 ConsoleSpecialKey.ControlBreak).SpecialKey, which allows you to determine whether the handler was invoked as a result of the user pressing Ctrl+C (the property value is ConsoleSpecialKey.ControlC) or Ctrl+Break (the property value is ConsoleSpecialKey.ControlBreak).

  • Cancel를 어떻게 애플리케이션에 사용자에 게 응답 키를 눌러 Ctrl + C 또는 Ctrl + Break를 확인할 수 있습니다.Cancel, which allows you to determine how to your application should respond to the user pressing Ctrl+C or Ctrl+Break. 기본적으로 Cancel 속성은 false, 프로그램 종료 이벤트 처리기가 종료 될 때 실행이 원인입니다.By default, the Cancel property is false, which causes program execution to terminate when the event handler exits. 해당 속성을 변경 true 애플리케이션 실행을 계속 되도록 지정 합니다.Changing its property to true specifies that the application should continue to execute.

애플리케이션의 요구 사항이 단순한, 하는 경우 사용할 수 있습니다는 TreatControlCAsInput 대신이 이벤트는 속성입니다.If your application has simple requirements, you can use the TreatControlCAsInput property instead of this event. 이 속성을 설정 하 여 false, 사용자가 Ctrl + C를 누르면 애플리케이션을 항상 종료 되는 것을 확인할 수 있습니다.By setting this property to false, you can ensure that your application always exits if the user presses Ctrl+C. 로 설정 하 여 true, Ctrl + C를 눌러 애플리케이션을 종료 하지는 확인할 수 있습니다.By setting it to true, you can ensure that pressing Ctrl+C will not terminate the application.

이 이벤트에 대 한 이벤트 처리기는 스레드 풀 스레드에서 실행 됩니다.The event handler for this event is executed on a thread pool thread.

보안

UIPermission
안전한 최상위 창 및 하위 창을 수정 합니다.for modifying safe top-level windows and subwindows. 연결 된 열거형: SafeTopLevelWindowsAssociated enumeration: SafeTopLevelWindows

적용 대상

추가 정보