The source of the problems is that this simple request is simply not supported under Winforms.
Sounds weird? It is. Winforms is often painfully close to the hardware layers and while this may be quite interesting at times, it also may be just a pita..
((One hidden hint by Hans should be noted: In the KeyUp
you get told which key was released so you can keep track of as many keys as you want..))
But now for a direct solution that desn't require you to keep a bunch of bools
around and manage them in the KeyDown
and KeyUp
events..: Enter Keyboard.IsKeyDown.
With it code like this works:
Uses the Keyboard.IsKeyDown
to determine if a key is down.
e
is an instance of KeyEventArgs
.
if (Keyboard.IsKeyDown(Key.Return)) {
btnIsDown.Background = Brushes.Red; }
...
Of course you can ceck for multiple key as well:
if (Keyboard.IsKeyDown(Key.A) && Keyboard.IsKeyDown(Key.W)) ...
The only requirement is that you borrow this from WPF
:
First: Add the namespace:
using System.Windows.Input;
Then: Add two references to the project:
PresentationCore
WindowsBase
Now you can test the keyboard at any time, including the KeyPress
event..