简体   繁体   English

如何在 C# 控制台应用程序中忽略“Enter”键?

[英]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);
        }
    }
}

This ConsoleApp is suppose to input year、month、day from Console.此 ConsoleApp 假设从控制台输入年、月、日。 I want to disable key except digital numbers(0-9).我想禁用除数字(0-9)之外的键。

Now this is my code, generally, it works.现在这是我的代码,一般来说,它可以工作。

But, for example, I want to input "2020" to year, when I input "202" and press Enter, the cursor will jump to the beginning of this line.但是,例如我想输入“2020”到年份,当我输入“202”并回车时,cursor 会跳到这一行的开头。 It looks like the screenshot, Although it will not affect the final result.看起来像截图,虽然不会影响最终结果。

I want to Console ignore the Enter key press(nothing happen), How to do that please?我想控制台忽略 Enter 按键(没有任何反应),请问该怎么做?

My Sceenshot我的截图

This is how you can skip the enter key这是您可以跳过回车键的方法


    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM