问题
I'm writing an console application witch Displaying certain data on the console screen, than checking for user input from the keyboard and finally handleing it by need. all single threaded.
For that i tried using Keyboard.IsKeyDown Method from System.Windows.Input namespace. and visual studio wo'nt allow it. Does anyone knows why and can help me? I dont see other way implementing that logic using only one thread and no timer's.
回答1:
Use Console.ReadKey() to read input from the keyboard in a console application.
Note that this is a blocking call. If you don't want to block, combine with Console.KeyAvailable
. For example, this program will loop and display if a key is pressed every 10th of a second:
static void Main(string[] args)
{
do
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey();
Console.WriteLine(key.Key);
}
else
{
Console.WriteLine("No key pressed");
}
System.Threading.Thread.Sleep(100);
} while (true);
}
来源:https://stackoverflow.com/questions/43766287/use-keyboard-iskeydown-in-c-sharp-console-application