Check Keyboard Input Winforms

若如初见. 提交于 2019-11-30 06:09:44

问题


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.


回答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.




回答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.



来源:https://stackoverflow.com/questions/39208327/check-keyboard-input-winforms

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