Curious problem with console input in C#
When using Console.Read(), the implementation seems to think that as soon as you push en开发者_运维技巧ter, you've entered enough bytes for an eternity of reads. For example, if Read is called twice in a row, you can't enter one value on one line, push enter, and move to the next. Even if you only entered one character, Read just returns zero (Edit: Or one. I'm not too sure.). I've got this problem with ReadLine too. I'm trying to keep my console open for input after the program's terminated (I have a WPF app and used AllocConsole manually) and/or prompt the user for each individual slice of input. But it worketh not. Is there some button to ask it to block if there's no input available?
I wrote a Brainfuck interpreter, and the example programs from Wiki produce the intended result, if they don't use input.
What I want to do is enter one character, push enter, get that character as a char, repeat.
After your last edit I expect the piece of code below might provide either what you want or point you in the right direction.
public static int ReadLastKey()
{
int lastKey = -1;
for(;;)
{
ConsoleKeyInfo ki = Console.ReadKey();
if (ki.Key != ConsoleKey.Enter)
{
lastKey = (int)ki.KeyChar;
}
else
{
return lastKey;
}
}
}
The function ReadLastKey will read key strokes and return the last key pressed when you press enter.
Of course if you do not want multiple key presses to be recorded you can remove the loop and just use Console.ReadKey twice, once to get the key press and then a second time to wait for the enter key. Or some permutation of one of these.
Here is a simple version of the function that will allow only one key press and then wait for the enter key to be pressed. Note this is very simplistic, you might want to handle other exit conditions etc.
public static int ReadLastKey()
{
int lastKey = -1;
ConsoleKeyInfo ki;
// Read initial key press
ki = Console.ReadKey();
// If it is enter then return -1
if (ki.Key == ConsoleKey.Enter) return lastKey;
lastKey = (int)ki.KeyChar;
// Wait for the user to press enter before returning the last key presss,
// and do not display key the errant key presses.
do
{
ki = Console.ReadKey(true);
} while (ki.Key != ConsoleKey.Enter);
return lastKey;
}
精彩评论