(C#) 如何在.NET控制台应用程序中判断按键是否按住

huangapple go评论59阅读模式
英文:

(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!");
}

huangapple
  • 本文由 发表于 2023年3月4日 01:22:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630116.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定