控制台应用程序等待密钥

时间:2013-04-08 15:01:41

标签: c# console

我目前正在研究c#中的roguelike。 世界,玩家等在控制台内呈现。但是当控制台中有太多变化时,它会滞后。 为了绕过这个,我试图让程序等待玩家取消按下玩家按下的键。 任何人都知道如何制作这个? 不好,没有类似Console.ReadKeyUp()的内容。

while(Console.KeyAvailable){
}

似乎不起作用......

以下是一些代码:

public void move(){
            if(!MainClass.loading){
                switch(Console.ReadKey().Key){
                    case ConsoleKey.NumPad8:
                        //walk up
                        break;
                    case ConsoleKey.NumPad4:
                        //walk left
                        break;
                    case ConsoleKey.NumPad6:
                        //walk right
                        break;
                    case ConsoleKey.NumPad2:
                        //walk down
                        break;
                    case ConsoleKey.NumPad7:
                        //walk left up
                        break;
                    case ConsoleKey.NumPad9:
                        //walk right up
                        break;
                    case ConsoleKey.NumPad1:
                        //walk left down
                        break;
                    case ConsoleKey.NumPad3:
                        //walk right down
                        break;
                    case ConsoleKey.NumPad5:
                        //eat
                        break;
                }

            }

        }

这就是它的样子:

enter image description here

1 个答案:

答案 0 :(得分:2)

如果不将此应用程序重构为事件驱动格式(带有消息循环的隐藏窗口等),您最好的选择可能是挖掘WinAPI中可用的各种功能。这样的事情可能有用:

 [DllImport("user32.dll")]
 [return: MarshalAs(UnmanagedType.Bool)]
 static extern bool GetKeyboardState(byte [] lpKeyState);

您可以使用此功能查询完整的键盘状态 - 它返回一个包含键盘状态的256字节数组。请参阅:here for more和一些示例。

例如,您也可以使用Console.ReadKey()然后阻止,直到GetKeyState()返回相关密钥的低位0

 [DllImport("user32.dll")]
 static extern short GetKeyState(VirtualKeyStates nVirtKey);

请参阅:here for more和示例。

MSDN:GetKeyState; GetKeyboardState

相关问题