英文:
(C#) How to know if a key is held down in .NET Console Application
问题
I want to know, if a key is held down by the user. I know how to do that in WinForms, but no clue in Console App. I don't want to download any C++ libraries or anything. Just want to know if you can do that using the System
namespace.
So, as you know, Console.ReadKey()
stops the application until a key is pressed. I tried doing Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape
in an if
statement (of course I also used else
after that to change things back to false
). It worked at first glance, but there is an obvious lag between key press and the reaction.
I would appreciate any help.
英文:
I want to know, if a key is held down by the user. I know how to do that in WinForms, but no clue in Console App. I don't want to download any C++ libraries or anything. Just want to know if you can do that using the System
namespace.
So, as you know, Console.ReadKey()
stops the application until a key is pressed. I tried doing Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape
in an if
statement (of course I also used else
after that to change things back to false
). It worked at first glance, but there is an obvious lag between key press and the reaction.
I would appreciate any help.
答案1
得分: 1
这可以通过使用 "while" 语句来实现。
例如:
while (Console.ReadKey().Key == ConsoleKey.Escape)
{
Console.WriteLine("Hello, World!");
}
英文:
This can be achieved using a "while" statement.
For example:
while (Console.ReadKey().Key == ConsoleKey.Escape)
{
Console.WriteLine("Hello, World!");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论