如何检测是否以C#形式按下了多个键 [英] How to detect if multiple keys are pressed in C# forms

查看:106
本文介绍了如何检测是否以C#形式按下了多个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种解决方案来检测是否在 C#中按下了多个键(我找不到解决方案!). 我有两个玩家玩这个游戏,我需要检测是否按下了一个键来移动他们. (我正在使用C#表单) 我只找到了答案,可以检测是否同时按下了两个键并且它们没有帮助.

I have looked for a solution to detect if multiple keys are pressed in C# (I couldn't find a solution!). I have this game with two players and I need to detect if a key is pressed to move them around. (I'm Using C# Forms) I've only found answers to detect if two keys are held down at the same time and they didn't help.

-编辑-

如何使用KeyPressed(C#)检测按键是否被按下

How to detect if a key is pressed using KeyPressed (C#)

推荐答案

问题的根源是Winforms根本不支持此简单请求.

The source of the problems is that this simple request is simply not supported under Winforms.

听起来很奇怪?它是. Winforms通常非常痛苦地靠近硬件层,尽管有时这可能很有趣,但也可能只是一个皮塔饼.

Sounds weird? It is. Winforms is often painfully close to the hardware layers and while this may be quite interesting at times, it also may be just a pita..

((应该注意Hans的一个隐藏提示:在KeyUp中,您会被告知释放了哪个键,以便可以随时跟踪所需的键.)

((One hidden hint by Hans should be noted: In the KeyUp you get told which key was released so you can keep track of as many keys as you want..))

但是,对于直接解决方案而言,它不需要您保持一堆bools并在KeyDown KeyUp事件中对其进行管理..:输入 Keyboard.IsKeyDown .

But now for a direct solution that desn't require you to keep a bunch of bools around and manage them in the KeyDown and KeyUp events..: Enter Keyboard.IsKeyDown.

使用它的代码如下:

使用Keyboard.IsKeyDown确定键是否按下. eKeyEventArgs的实例.

Uses the Keyboard.IsKeyDown to determine if a key is down. e is an instance of KeyEventArgs.

if (Keyboard.IsKeyDown(Key.Return)) {
    btnIsDown.Background = Brushes.Red; }
...

当然,您也可以选择多个键:

Of course you can ceck for multiple key as well:

if (Keyboard.IsKeyDown(Key.A) && Keyboard.IsKeyDown(Key.W)) ...

唯一的要求是您从WPF借用:

The only requirement is that you borrow this from WPF:

首先:添加名称空间:

using System.Windows.Input;

然后:向项目添加两个引用:

Then: Add two references to the project:

PresentationCore
WindowsBase

现在您可以随时测试键盘,包括KeyPress事件.

Now you can test the keyboard at any time, including the KeyPress event..

这篇关于如何检测是否以C#形式按下了多个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆