Use Keyboard.IsKeyDown in C# console application

梦想的初衷 提交于 2019-12-25 07:45:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!