How to determine if a key is pressed

How to determine if any keyboard key is pressed? I'm not interested in what a key is, I just want to know if the key is all pressed.

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

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

you could do:

if(KeysDown().Any()) //...
+7
source

If you want to detect a key pressed only in our application (when the WPF window is activated), add KeyDownas shown 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, it is a little more complicated, but positive. I recommend RegisterHotKey(defines a hotkey for the entire system) UnregisterHotKeyfrom the Windows API. Try using them in C # from pinvoke.net or these tutorials:

Thse - Microsoft.

. , , .

+4

System.Windows.Input.Key.

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

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

        return false;
    }
+2

... , GetKeyboardState():

.

KeyDown/KeyUp ... .

, KeyDown/KeyUp.... , .

, , , , ( )... KeyDown KeyUp ... .... GetKeyboardState() Keyboard.IsKeyDown.

( , )

+1

All Articles