Roy T.
Roy T.

Reputation: 9638

Keyboard.Modifiers is None when pressing the Windows modifier key

The Surface Pen sends the signal WindowsKey+F20/19 whenever the button on the back is clicked or double clicked and I would like to capture this in my application.

I've seen some questions about detecting when the Windows Key is pressed and it seems this is not possible in C# without PInvoke.

However, I'm not sure if this also applies to the Windows Key as a modifier. It seems so, but I'd like to know for sure.

The ModifierKeys enum documentation lists the Windows Key and there seem to be no special remarks regarding this key.

So I've wired up the main window's OnPreviewKeyDown even to this code:

private void MainWindow_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.SystemKey == Key.F10 &&
         e.KeyboardDevice.Modifiers.HasFlag(System.Windows.Input.ModifierKeys.Windows)
      {
        Console.WriteLine("Succes!");
    }
}

This code works if I listen to the alt modifier key, however if I press Windows+F10 e.KeyboardDevice.Modifiers equals None and thus the if condition fails.

Is there anything I'm missing or should I go the PInvoke route?

Upvotes: 4

Views: 1281

Answers (1)

mm8
mm8

Reputation: 169300

The following code should be able to detect Windows+F10:

private void MainWindow_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.SystemKey == Key.F10 && (Keyboard.IsKeyDown(Key.LWin) || Keyboard.IsKeyDown(Key.RWin)))
    {
        Console.WriteLine("Succes!");
    }
}

Upvotes: 2

Related Questions