RobHurd
RobHurd

Reputation: 2061

How to detect if any key is pressed

How can I detect if any keyboard key is currently being pressed? I'm not interested in what the key is, I just want to know if any key is still pressed down.

if (Keyboard.IsKeyDown(Key.ANYKEY??)
{

}

Upvotes: 9

Views: 45447

Answers (4)

franssu
franssu

Reputation: 2430

Iterate over the System.Windows.Input.Key enum values.

public static bool IsAnyKeyDown()
{
    var values = Enum.GetValues(typeof(Key));

    foreach (var v in values)
        if (((Key)v) != Key.None && Keyboard.IsKeyDown((Key)v)
            return true;

    return false;
}

Upvotes: 3

Colin Smith
Colin Smith

Reputation: 12540

Good answer here...get the set of all the keystates at once using GetKeyboardState():

The above is checking the live state of the keyboard.

If you rely on hooking events up to the KeyDown/KeyUp events to track the state of the keyboard...then this may not be so accurate.

That's becuase you are relying on the message pumping to process and dispatch those KeyDown/KeyUp messages....they may be delivered after the real keyboard state has changed again.

Also because when your bit of code that is interested in the keyboard state is running (usually on the UI thread)...the KeyDown or KeyUp can't interrupt you...as they are dispatched on the UI thread too....that's why using GetKeyBoardState() or the Keyboard.IsKeyDown should be used.

(the above is assuming you want and care about the live state)

Upvotes: 1

Servy
Servy

Reputation: 203819

public static IEnumerable<Key> KeysDown()
{
    foreach (Key key in Enum.GetValues(typeof(Key)))
    {
        if (Keyboard.IsKeyDown(key))
            yield return key;
    }
}

you could then do:

if(KeysDown().Any()) //...

Upvotes: 13

Ionică Bizău
Ionică Bizău

Reputation: 113365

If you want to detect key pressed only in our application (when your WPF window is activated) add KeyDown like below:

public MainWindow()
{
    InitializeComponent();
    this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
}

void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
    MessageBox.Show("You pressed a keyboard key.");
}

If you want to detect when a key is pressed even your WPF window is not active is a little harder but posibile. I recomend RegisterHotKey (Defines a system-wide hot key) and UnregisterHotKey from Windows API. Try using these in C# from pinvoke.net or these tutorials:

Thse is a sample in Microsoft Forums.

You will use Virtual-Key Codes. I Hope that I was clear and you will understand my answer.

Upvotes: 7

Related Questions