How to get IsKeyDown method to work in C#
Solution 1
Add PresentationCore.dll
assembly as a reference.
Add WindowsBase.dll
assembly as a reference.
Test code:
private void buttonMisc_Click(object sender, EventArgs e)
{
if (System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key.LeftShift) == true)
MessageBox.Show("Got it!");
}
Solution 2
IsKeyDown is static, so you need to use it like
Keyboard.IsKeyDown()
Not with an instantiated object.
You also need to make sure you have the correct using statement at the top:
using System.Windows.Input;
EDIT
On further inspection, Keyboard is a static class... So you can't Keyboard test = new Keyboard();
Related videos on Youtube
Comments
-
FrostyFire over 1 year
I can’t figure out how get this method to work:
System.Windows.Input.Keyboard.IsKeyDown(System.Windows.Input.Key)
The object browser says the following:
public static bool IsKeyDown(System.Windows.Input.Key key)
Member of System.Windows.Input.Keyboard
Summary:
Determines whether the specified key is pressed.
Parameters:
key: The specified key.
Return Values:
true if key is in the down state; otherwise, false.Okay, so it’s a member of Keyboard, right? I used the following code: Keyboard test = new Keyboard();
But when I type test and then the dot, IsKeyDown is not an option. The only options are from the Windows.Forms members. What am I missing here? Thanks.
-
FrostyFire over 11 yearsI'm not sure what you mean. As I type your code, after pressing the dot, the method does not come up. Do I need to add a special reference aside from PresentationCore?
-
Justin Self over 11 years@user1739957 You should be able to simply type
Keyboard.IsKeyDown(Key.A)
-
FrostyFire over 11 yearsNope! Its not an option after I type the dote!
-
Yinda Yin over 11 yearsSo you're detecting a key down when the user is clicking a button with the mouse? :/
-
Steve Wellens over 11 yearsYep. I get the message box when I hold the left shift down and click the button with the mouse.
-
Justin Self over 11 years@user1739957 If you have Keyboard test = new Keyboard, you need to remove that because it won't compile.
-
FrostyFire over 11 yearsThanks so much, Steve Wellens. It worked great. I altered it a little and it works even when the form is minimized. As a matter of fact when I pressed shift for the first letter, the message came up. Thanks again!
-
JonP about 8 yearsThis helped me to detect if Left Shift is held down when a menu item is clicked. The Microsoft help for
IsKeyDown
is incomplete, it mentions that you need assembly PresentationCore (which provides theKeyboard
class) but fails to mention WindowsBase (which provides theKey
class with all the key definitions).