How to detect if any 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:
- Global Hotkeys: Register a hotkey that is triggered even when form isn't focused.
- Simple steps to enable Hotkey and ShortcutInput user control
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.