C#控制台应用如何检测用户是否按下指定数字或字母按键
C# 控制台按键绑定命令实现
你可以基于现有代码扩展如下逻辑,实现按键监听与对应命令触发:
using System; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine("Hello,[user]!"); Console.WriteLine("请输入你的用户名"); string uname = Console.ReadLine(); Thread.Sleep(1000); Console.Clear(); Thread.Sleep(1500); Console.WriteLine("欢迎来到Axiom, " + uname); Console.WriteLine("如需查看完整命令列表,请按数字1"); Console.WriteLine("无需查看可直接按下对应命令按键执行功能,按Esc键可退出程序"); // 新增按键监听逻辑 while (true) { // 读取按键,intercept设为true避免按键字符回显到控制台 ConsoleKeyInfo pressedKey = Console.ReadKey(intercept: true); switch (pressedKey.Key) { // 主键区数字1 case ConsoleKey.D1: Console.WriteLine("\n===== 全量命令列表 ====="); Console.WriteLine("1: 查看命令列表"); Console.WriteLine("2: 执行功能A"); Console.WriteLine("3: 执行功能B"); Console.WriteLine("Esc: 退出程序"); break; // 主键区数字2 case ConsoleKey.D2: Console.WriteLine("\n正在执行功能A..."); // 此处补充功能A的业务逻辑 break; // 主键区数字3 case ConsoleKey.D3: Console.WriteLine("\n正在执行功能B..."); // 此处补充功能B的业务逻辑 break; // Esc退出键 case ConsoleKey.Escape: Console.WriteLine("\n正在退出程序..."); Thread.Sleep(1000); return; // 未定义的按键 default: Console.WriteLine($"\n未识别的按键:{pressedKey.KeyChar},请按1查看支持的命令"); break; } } } }
关键实现说明
Console.ReadKey(true)是核心方法,参数设为true时不会把用户按下的字符打印到控制台,交互更整洁- 用死循环持续监听用户按键操作,直到触发Esc对应的退出逻辑才会终止程序
- 以上代码仅适配主键区的数字按键,如果需要支持小键盘数字,额外新增
ConsoleKey.NumPad1、ConsoleKey.NumPad2等枚举对应的case即可 - 你可以根据实际业务需求新增更多case,绑定不同按键对应的命令逻辑
内容的提问来源于stack exchange,提问作者Blue_A55T
相关产品推荐
相关产品推荐

