Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 734
Roy T. Avatar asked Sep 06 '25 02:09

Roy T.


1 Answers

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!");
    }
}
like image 105
mm8 Avatar answered Sep 07 '25 19:09

mm8