【问题标题】:Scan for key press in Console without pausing it在控制台中扫描按键而不暂停
【发布时间】:2013-06-30 17:00:23
【问题描述】:

我有这个问题。我有用于在控制台中绘制文本的 while 循环,我想让它具有交互性。我有两个 if 语句,其中包含实际键的条件。 因此,如果我按“W”,它会做一些事情,但这不起作用。我有两个项目,engine.dll 和 testApp 用于测试。代码如下:

 while (true)
            {
                game g = new game();
                g.Draw(cHP, mHP, name,posX,posY,blip);
                Thread.Sleep(50);
                Console.CursorVisible = false;
                ConsoleKeyInfo cki = new ConsoleKeyInfo();
                //if (Console.KeyAvailable) { Console.CursorVisible = true; break; }
                if (cki.KeyChar == 'w') MoveY(1); // Here it is
                if (cki.KeyChar == 's') MoveY(-1); // and here
            }

【问题讨论】:

  • 不要使用 thread.sleep 作为开始,将 readkey 放在后台工作人员上,然后在它完成时做一些事情(如果这甚至可以工作的话)
  • Console.KeyAvailable 有什么问题?
  • @zmbq - 以前从未见过,非常好
  • 据我所知,Console.KeyAvailable 只是控制是否点击了任何键。它的布尔值,我不需要使用它。
  • 不确定您的设计是什么,但很可能game g = new game(); 行应该是BEFORE while 循环......

标签: c# windows dll console


【解决方案1】:

不确定您在最终版本中想要什么,但对您现有代码的修复将是这样的

 Console.CursorVisible = false;
 while(true)
 {
       game g = new game();
       g.Draw(cHP, mHP, name,posX,posY,blip);
       Thread.Sleep(50); //might not be required depending
                         //on what you want to do

       var cki = Console.ReadKey(true);
       if (cki.KeyChar == 'w') MoveY(1);// Here it is
       if (cki.KeyChar == 's') MoveY(-1); // and here
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 2010-12-18
    • 2017-07-12
    相关资源
    最近更新 更多