【问题标题】:How to read a key pressed by the user and display it on the console?如何读取用户按下的键并将其显示在控制台上?
【发布时间】:2011-03-05 08:01:05
【问题描述】:

我试图询问用户“输入任何键”,当按下该键时,它会显示“您按下了‘键’”。你能帮忙看看这段代码有什么问题吗?

这是我写的:

using System;
class Program
{
    public static void Main(string[] args)
    {      
        Console.Write("Enter any Key: ");
        char name = Console.Read();
        Console.WriteLine("You pressed {0}", name);
    }
}

【问题讨论】:

标签: c# console keyboard


【解决方案1】:

试试

Console.WriteLine("Enter any Key: ");
ConsoleKeyInfo name = Console.ReadKey();
Console.WriteLine("You pressed {0}", name.KeyChar);

【讨论】:

  • 不是在输出中显示特定的键,而是将输出显示为“您按下了 System.ConsoleKeyInfo
  • 你把最后一行“name”改成“name.KeyChar”了吗?
  • 我改了,现在好了,干杯!
【解决方案2】:

Console.Read() 在用户按下 Enter 时做出反应,并返回用户在按下 Enter 之前键入的整个字符串。要读取一个按键,请使用

Console.ReadKey()

【讨论】:

  • 我按照你说的做了,现在出现了这个错误。 "不能将类型 'System.ConsoleKeyInfo' 隐式转换为 'char'
  • 是的,Console.ReadKey() 返回一个ConsoleKeyInfo,您可以从中获得带有name.KeyChar 的字符,正如哈里约特在他的回答中所显示的那样。
【解决方案3】:
Console.Write("Enter any Key: ");
char name = (char)Console.Read();
Console.WriteLine("You pressed {0}", name); 

问题是 Console.Read() 返回一个整数,而不是一个字符。

但是,int 可以通过强制转换转换为 char。因此,如果您将 (char) 放在 read 语句的前面,C# 会将其转换为 char 并且可以正常工作。

【讨论】:

    【解决方案4】:
    string keypress = "";
    
    Console.Write("Enter any key: ");
    keypress = Console.ReadLine();
    Console.Write("\nYou pressed {0}",keypress);
    

    【讨论】:

      【解决方案5】:
      {
          Console.Write("Enter any Key: ");
          char name = Convert.ToChar(Console.ReadLine());
          Console.WriteLine("You pressed {0}", name);
      
          Console.ReadKey();
      }
      

      【讨论】:

        【解决方案6】:

        使用Console.ReadKey() 而不是Read()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-10
          • 2018-05-22
          • 1970-01-01
          • 1970-01-01
          • 2018-04-06
          相关资源
          最近更新 更多