简体   繁体   English

如何在C#中同时检测多个按键?

[英]How to detect more than one keypress simultaneously in C#?

I am working on a map editor for my game and I use the arrow keys to scroll around the map area. 我正在为自己的游戏使用地图编辑器,并且使用箭头键在地图区域中滚动。 Currently I'm using the KeyDown event, which works fine for scrolling up, down, left or right - but my question would be how to allow diagonal scrolling. 目前,我正在使用KeyDown事件,该事件在向上,向下,向左或向右滚动时效果很好-但我的问题是如何允许对角线滚动。 Currently, if I hold the right-arrow and then (whilst keeping the right-arrow held) I then press and hold the down-arrow, the down direction replaces the scrolling to the right instead of scrolling diagonally to the bottom right. 当前,如果我按住右箭头,然后(按住右箭头)然后按住向下箭头,那么向下方向将代替向右滚动,而不是对角滚动至右下角。

Is there a way, for instance, that I could check whether another arrow key is being pressed whilst in the KeyDown event? 例如,有没有一种方法可以检查在KeyDown事件中是否按下了另一个箭头键? How can I respond to more than one key being held? 如何应对不止一个键被按住的问题?

Thanks 谢谢

Not easily, the key-down of the 2nd keystroke stops the 1st one from repeating. 不容易,第二次击键的按下会阻止第一次重复。 What you have to do is record that the key is down in the KeyDown event. 您要做的是在KeyDown事件中记录该键已按下。 Cancel that state in the KeyUp event. 在KeyUp事件中取消该状态。 Next, use a Timer (~250 msec) and in its Tick event check the state of the keys. 接下来,使用计时器(约250毫秒),并在其Tick事件中检查按键的状态。

The easiest way to do this is to use a Windows API call to get the state of every key on they keyboard, and then check the keys you are interested in: GetKeyboardState via PInvoke . 最简单的方法是使用Windows API调用获取键盘上每个键的状态,然后检查您感兴趣的键: 通过PInvoke获得GetKeyboardState

You can call it on KeyDown/KeyUp, check the state of the keyboard, and act appropriately. 您可以在KeyDown / KeyUp上调用它,检查键盘的状态并采取适当的措施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM