'Check Keyboard Input 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.");
}

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.

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



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2