Handling Ctrl+C in C#: Customizing Console Behavior with `Console.TreatControlCAsInput`

Learn how to customize your console application's response to Ctrl+C keyboard interrupts using C#'s `Console.TreatControlCAsInput` property. This tutorial explains how to handle Ctrl+C as regular input, enabling more sophisticated control over console application termination.



Handling Ctrl+C in C# Using `Console.TreatControlCAsInput`

The C# `Console.TreatControlCAsInput` property controls how the console handles the Ctrl+C keyboard shortcut. By default, Ctrl+C terminates the console application. However, setting `TreatControlCAsInput` to `true` allows you to handle Ctrl+C as regular input within your application.

Understanding `Console.TreatControlCAsInput`

The `Console.TreatControlCAsInput` property (a static property of the `System.Console` class) determines how Ctrl+C is interpreted by the console. It's a boolean property; `true` means Ctrl+C is treated as regular input; `false` means it terminates the application. This property affects how your console application responds to Ctrl+C.

`Console.TreatControlCAsInput` Syntax


Console.TreatControlCAsInput = true; // Or false

Setting the property to `true` enables custom handling of Ctrl+C; setting it to `false` restores the default interrupt behavior. Note that attempting to get or set this property when the console is not available will throw an `IOException`.

Example 1: Handling Ctrl+C as Input


using System;

public class CtrlCHandler {
    public static void Main(string[] args) {
        Console.WriteLine("Press Ctrl+C to test.");
        Console.TreatControlCAsInput = true; // Treat Ctrl+C as input
        while (true) {
            // ... (read key presses; handle Ctrl+C as regular input) ...
        }
    }
}

Example 2: Handling Multiple Key Combinations


using System;

public class KeyHandler {
    public static void Main(string[] args) {
        Console.TreatControlCAsInput = true;
        Console.WriteLine("Press any key (Escape to quit).");
        // ... (loop to read key presses with modifiers and print) ...
    }
}

Example 3: Ctrl+C as Interrupt


using System;

public class CtrlCHandler {
    public static void Main(string[] args) {
        Console.WriteLine("Press Ctrl+C to exit.");
        Console.TreatControlCAsInput = false; // Ctrl+C will terminate the app
        while (true) {
          // ... (code to read key presses, checking for Ctrl+C to exit gracefully) ...
        }
    }
}