Console.TreatControlCAsInput Property in C# with examples
Last Updated :
14 Feb, 2023
Console.TreatControlCAsInput Property is used to get or set a value indicating whether the combination of the Control modifier key and C console key (Ctrl+C) is treated as ordinary input or as an interruption that is handled by the operating system.
Syntax:
public static bool TreatControlCAsInput { get; set; }
Property Value: This property returns true if Ctrl+C is treated as ordinary input. Otherwise false, it means if the input is Ctrl+C then the program is terminated. Exception: This property will give IOException if the program is not able to get or set the input mode of the console input buffer.
Below programs illustrate the use of the above-discussed property:
Example 1:
csharp
using System;
class GFG {
public static void Main()
{
ConsoleKeyInfo c;
Console.TreatControlCAsInput = true ;
Console.WriteLine("Press any key with combination of CTL, "+
"ALT, and SHIFT or Press the Esc to quit: \n");
do {
c = Console.ReadKey();
Console.Write(" - pressed key is ");
Console.WriteLine(c.Key.ToString());
} while (c.Key != ConsoleKey.Escape);
}
}
|
Output:
Example 2:
csharp
using System;
class GFG {
public static void Main()
{
ConsoleKeyInfo c;
Console.TreatControlCAsInput = true ;
Console.WriteLine("Press any key with combination of CTL, "+
"ALT, and SHIFT or Press the Esc to quit: \n");
do {
c = Console.ReadKey();
Console.Write("pressed key is ");
if ((c.Modifiers & ConsoleModifiers.Shift) != 0)
Console.Write("SHIFT + ");
if ((c.Modifiers & ConsoleModifiers.Control) != 0)
Console.Write("CTRL + ");
if ((c.Modifiers & ConsoleModifiers.Alt) != 0)
Console.Write("ALT + ");
Console.WriteLine(c.Key.ToString());
} while (c.Key != ConsoleKey.Escape);
}
}
|
Output:
When false
csharp
using System;
class GFG {
public static void Main()
{
ConsoleKeyInfo c;
Console.TreatControlCAsInput = false ;
Console.WriteLine("Press any key with combination of CTL,"+
" ALT, and SHIFT or Press the Esc to quit: \n");
do {
c = Console.ReadKey();
Console.Write(" - pressed key is ");
Console.WriteLine(c.Key.ToString());
} while (c.Key != ConsoleKey.Escape);
}
}
|
Output :
Press any key with combination of CTL, ALT, and SHIFT or Press the Esc to quit:
a - pressed key is A
b - pressed key is B
g - pressed key is G
// Here after these input we press Ctrl+C,
// then the program is terminated.
Reference:
Share your thoughts in the comments
Please Login to comment...