检查键盘输入Winforms

本文关键字:Winforms 输入 键盘 检查 | 更新日期: 2023-09-27 18:04:37

我想知道如果不这样做

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

我可以设置一个bool方法,这样做:

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

我在这里坐了好长时间,想弄清楚该怎么做。但我就是不明白。

如果你想知道,我的计划是在一个不同的方法中调用bool来检查输入

检查键盘输入Winforms

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

但是在某些情况下,我想你想要检查一个特定的键是否在某个进程的中间,所以你可以这样使用GetKeyState方法:

[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

这是你要找的吗?

private bool KeyDown(KeyEventArgs e, Keys key)
{
    if(e.KeyCode == key)
        return true;
    return false;
}

然后像

一样使用
protected override void OnKeyDown(KeyEventArgs e)
{
    if(KeyCode(e, Keys.A))
    {
        //do whatever
    }
    else if (KeyCode (e, Keys.B))
    {
         //do whatever
    }
    // so on and so forth
}

HTH .


根据你的评论下面的代码可以工作。但是请记住,对于面向对象的设计,不建议这样做。

class FormBase: Form
{
    private Keys keys;
    protected override void OnKeyDown(KeyEventArgs e)
    {
         keys = e.KeyCode;
    }   
    protected bool KeyDown(Keys key)
    {
        if(keys == key)
            return true;
        return false;
    }
}

现在从这个类派生Form类而不是System.Windows.Forms.Form类,并使用如下函数:

public class MyForm: FormBase
{
    protected override void OnKeyPress(KeyEventArgs e)
    {
        if(KeyDown(Keys.A))
        {
            //do something when 'A' is pressed
        }
        else if (KeyDown(Keys.B))
        {
            //do something when 'B' is pressed
        }
        else
        {
            //something else
        }
    }
}

我希望这是你正在寻找的