Check Keyboard Input Winforms

六月ゝ 毕业季﹏ 提交于 2019-11-28 14:50:30

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);
}

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.

Is this what you are looking for?

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

    return false;
}

Then use it like

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.


As per your comment the following code will work. But remember that this is not recommended for object oriented design.

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;
    }
}

Now derive your Form classes from this class instead of System.Windows.Forms.Form class and use the function as below:

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
        }
    }
}

I hope this is what you are looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!