Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...