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??)
{
}
To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.
Go to Start , then select Settings > Accessibility > Keyboard, and turn on the On-Screen Keyboard toggle. A keyboard that can be used to move around the screen and enter text will appear on the screen. The keyboard will remain on the screen until you close it.
Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.
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()) //...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With