【问题标题】:Detect if a key is down without waiting for key press in C# console application [duplicate]在 C# 控制台应用程序中检测按键是否按下而不等待按键 [重复]
【发布时间】:2013-12-07 21:34:48
【问题描述】:

如何检查某个键是否按下,如果按下另一个键或未按下任何键,则不执行任何操作?

我想要在 Visual C# 控制台应用程序中使用类似这样的伪代码:

while (true) {
    if (IsKeyDown(Escape)) { //checks if Escape is down
        println("Press enter to resume");
        waitKey(Enter); //waits until Enter is pressed
    }
    //do something
}

此循环将继续执行某些操作,直到按下 Escape 键。如果按下 Escape 键,循环将暂停,直到按下 Enter 键。

我试过了:

  • Console.ReadKey() - 将暂停循环,直到按下任意键。
  • Keyboard.IsKeyDown() - 在控制台应用程序中无效。

【问题讨论】:

标签: c# .net console-application keydown keyevent


【解决方案1】:

这是你要找的吗?

using System;

class Example 
{
  public static void Main() 
  {
    ConsoleKeyInfo cki;
    // Prevent example from ending if CTL+C is pressed.
    Console.TreatControlCAsInput = true;

    Console.WriteLine("Press any combination of CTL, ALT, and SHIFT, and a console key.");
    Console.WriteLine("Press the Escape (Esc) key to quit: \n");
    do 
    {
       cki = Console.ReadKey();
       Console.Write(" --- You pressed ");
       if((cki.Modifiers & ConsoleModifiers.Alt) != 0) Console.Write("ALT+");
       if((cki.Modifiers & ConsoleModifiers.Shift) != 0) Console.Write("SHIFT+");
       if((cki.Modifiers & ConsoleModifiers.Control) != 0) Console.Write("CTL+");
       Console.WriteLine(cki.Key.ToString());
     } while (cki.Key != ConsoleKey.Escape);
  }
 }

http://msdn.microsoft.com/en-us/library/471w8d85%28v=vs.110%29.aspx

【讨论】:

  • 我有确切的答案... while(true) { Console.Write(DateTime.Now.ToString("ss ")); if (Console.KeyAvailable) { if (Console.ReadKey().Key == ConsoleKey.Escape) { do { Console.WriteLine("按回车键"); } 而 (Console.ReadKey().Key != ConsoleKey.Enter); } } Thread.Sleep(100);}
  • 我意识到这个问题已经结束,但是按照问题中的伪代码为这个问题提供确切的代码示例答案会不会有帮助?
猜你喜欢
  • 2012-08-28
  • 1970-01-01
  • 2021-12-16
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
相关资源
最近更新 更多