简体   繁体   中英

Console.ReadKey(false) in C# something fishy about it

i am trying to make a simple application in C# in which every character I type is displayed in a console window. Here is my code :

class Program {
    static void Main(string[] args) {
        while (true) {
            System.ConsoleKeyInfo input;
            input = Console.ReadKey(false);
            String d = input.ToString();
            char c = d[0];
            Console.WriteLine(c);
        }
    }
}

The problem is that the characters are not displayed correctly, and to be more precise, every character is followed by an 'S'. For example i type 'a' and i get 'aS' instead of 'a'. Any solutions? Thnx in advance!

What you are seeing is the following:

  • The original character you entered, since you passed false not true to ReadKey
  • The first characters of the string "System.ConsoleKeyInfo", since the ToString() method returns the typename (here), not the character entered.

Use the following code instead to achieve what you attempted:

while(true)
{
    ConsoleKeyInfo info = Console.ReadKey(true);
    Console.WriteLine(info.KeyChar);
}

因为input.ToString() == "System.ConsoleKeyInfo" :-)根据您要执行的操作,请尝试编写input.KeyChar

The parameter of Console.ReadKey(false); defines if the key you type is intercepted or not. So Console.ReadKey(false); prints the character you type and Console.Writeline(c) prints the S .

Try char c = input.KeyChar; instead.

The problem is that you are using ToString() on a System.ConsoleKeyInfo . When this is turned into a string you will get "System.ConsoleKeyInfo" and the first character is therefore 'S' . Did you mean to write the following code instead?

while (true)
{
    var input = Console.ReadKey(false);
    Console.WriteLine(input.KeyChar);
}

With that code each character will get duplicated (so you will get aabbccddee ). Change the false to true in ReadKey to fix that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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