Console.TreatControlCAsInput属性用于获取或设置一个值,该值指示将Control修饰键和C控制台键(Ctrl + C)的组合视为普通输入还是操作系统处理的中断。
句法:
public static bool TreatControlCAsInput { get; set; }
属性值:如果将Ctrl + C视为普通输入,则此属性返回true。否则为false,表示如果输入为Ctrl + C,则程序将终止。
异常:如果程序无法获取或设置控制台输入缓冲区的输入模式,则此属性将提供IOException。
下面的程序说明了上面讨论的属性的用法:
范例1:
// C# program to illustrate the use of
// Console.TreatControlCAsInput Property
using System;
class GFG {
// Main Method
public static void Main()
{
ConsoleKeyInfo c;
// Prevent program from terminating
// if CTL+C is pressed.
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 ");
// only prints the pressed keys
Console.WriteLine(c.Key.ToString());
// condition for Exit
} while (c.Key != ConsoleKey.Escape);
}
}
输出:
范例2:
// C# program to illustrate the use of
// Console.TreatControlCAsInput Property
using System;
class GFG {
// Main Method
public static void Main()
{
ConsoleKeyInfo c;
// Prevent program from terminating
// if CTL+C is pressed.
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 ");
// conditions-
if ((c.Modifiers & ConsoleModifiers.Shift) != 0)
Console.Write("SHIFT + ");
if ((c.Modifiers & ConsoleModifiers.Control) != 0)
Console.Write("CTL + ");
if ((c.Modifiers & ConsoleModifiers.Alt) != 0)
Console.Write("ALT + ");
// prints the pressed keys
Console.WriteLine(c.Key.ToString());
// condition for Exit
} while (c.Key != ConsoleKey.Escape);
}
}
输出:
假的时候
using System;
class GFG {
// Main Method
public static void Main()
{
ConsoleKeyInfo c;
// Prevent program from terminating
// if CTL+C is pressed.
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 ");
// only prints the pressed keys
Console.WriteLine(c.Key.ToString());
// condition for Exit
} while (c.Key != ConsoleKey.Escape);
}
}
输出 :
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.
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.console.treatcontrolcasinput?view=netframework-4.7.2