在C#控制台应用程序中使用Keyboard.IsKeyDown [英] Use Keyboard.IsKeyDown in C# console application
问题描述
我正在编写一个控制台应用程序,在控制台屏幕上显示某些数据,而不是检查键盘上的用户输入并最终根据需要进行处理.所有单线程.
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.
为此,我尝试使用System.Windows.Input命名空间中的Keyboard.IsKeyDown方法.而Visual Studio则不允许这样做. 有谁知道为什么并且可以帮助我吗? 我看不到仅使用一个线程而不使用计时器来实现该逻辑的其他方法.
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.
推荐答案
Use Console.ReadKey()
to read input from the keyboard in a console application.
请注意,这是一个阻止呼叫.如果您不想阻止,请与Console.KeyAvailable
结合使用.例如,该程序将循环并显示每10秒是否按下一个键:
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);
}
这篇关于在C#控制台应用程序中使用Keyboard.IsKeyDown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!