Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...