C# – 控制台击键
我想比较在控制台中按下的键和左箭头键如果它们相等意味着按下的键是左箭头键,键将控制台的背景颜色改为青色……
我不知道如何设置If语句,因为我不知道如何在控制台中比较键。
using System; namespace ConsolePaint { class MainClass { public static void Main (string[] args) { ConsoleKeyInfo keypress; keypress = Console.ReadKey(); // read keystrokes if ( keypress.KeyChar == ConsoleKey.LeftArrow ) { Console.BackgroundColor = "Cyan"; } } } }
试试这个:
ConsoleKeyInfo keypress; keypress = Console.ReadKey(); // read keystrokes if (keypress.Key == ConsoleKey.LeftArrow) { Console.BackgroundColor = ConsoleColor.Cyan; }
你需要使用.KeyChar
(而不是.KeyChar
) – 你的"Cyan"
应该是ConsoleColors.Cyan
。
试试这个:
ConsoleKeyInfo keypress; keypress = Console.ReadKey(); // read keystrokes if ( (int)keypress.Key == (char)ConsoleKey.LeftArrow ) { Console.BackgroundColor = ConsoleColor.Cyan; }