检查键盘输入Winforms [英] Check Keyboard Input Winforms

查看:115
本文介绍了检查键盘输入Winforms的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否不是这样做

I was wondering if instead of doing this

protected override void OnKeyDown(KeyEventArgs e)
{
    if (e.KeyCode == Keys.A)
        Console.WriteLine("The A key is down.");
}

我可以设置bool方法并执行以下操作:

I could set up a bool method and do this:

if(KeyDown(Keys.A))
// do whatever here

我坐在这里已经很久了,试图弄清楚该怎么做.但是我只是不能把头缠住它.

I've been sitting here for ages trying to figure out how to do it. But I just can't wrap my head around it.

如果您想知道,我的计划是在另一个方法中调用bool,以检查输入.

In case you were wondering, my plan is to call the bool inside a different method, to check for input.

推荐答案

由于您通常希望在按下某个键后立即执行操作,因此通常使用KeyDown事件就足够了.

Since you usually want to perform an action immediately after pressing a key, usually using a KeyDown event is enough.

但是在某些情况下,我想您想检查某个过程中某个特定键是否已关闭,因此您可以使用

But in some cases I suppose you want to check if a specific key is down in middle of a some process, so you can use GetKeyState method this way:

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern short GetKeyState(int keyCode);
public const int KEY_PRESSED = 0x8000;
public static bool IsKeyDown(Keys key)
{
    return Convert.ToBoolean(GetKeyState((int)key) & KEY_PRESSED);
}

您应该知道,每次使用例如IsKeyDown(Keys.A)来检查键状态时,如果在检查状态时按下了键,该方法都会返回true.

You should know, each time you check the key state using for example IsKeyDown(Keys.A) the method returns true if the key is pressed at the moment of checking the state.

这篇关于检查键盘输入Winforms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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