簡體   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);
        }
    }
}

此 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM