[英]How to ignore “Enter” key press in C# Console Application?
using System;
using System.Text;
namespace 判断输入是否为数字
{
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
char temp = Console.ReadKey().KeyChar;
if (char.IsDigit(temp))
{
news[i] = temp;
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}
}
此 ConsoleApp 假设从控制台输入年、月、日。 我想禁用除数字(0-9)之外的键。
现在这是我的代码,一般来说,它可以工作。
但是,例如我想输入“2020”到年份,当我输入“202”并回车时,cursor 会跳到这一行的开头。 看起来像截图,虽然不会影响最终结果。
我想控制台忽略 Enter 按键(没有任何反应),请问该怎么做?
这是您可以跳过回车键的方法
internal class Program
{
public static int ConsoleInputDigit(int length)
{
char[] news = new char[length];
for (int i = 0; i < news.Length; i++)
{
var key = Console.ReadKey();
if (key.KeyChar.IsDigit(temp))
{
news[i] = temp;
}
else if(key == ConsoleKey.Enter)
{
// ignore
}
else
{
Console.Write("\b \b");
i--;
}
}
return int.Parse(new string(news));
}
public static void Main(string[] args)
{
Console.Write("Input Year:");
int y = ConsoleInputDigit(4);
Console.Write("\nInput Month:");
int m = ConsoleInputDigit(2);
Console.Write("\nInput Day:");
int d = ConsoleInputDigit(2);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.