1

In a WPF MVVM application I need to trigger a command when CTRL+' (control and apostrophe) is pressed. None of the following will compile...

<KeyBinding Modifiers="CTRL" Key="'" Command="{Binding MyCommand}"/>
<KeyBinding Modifiers="CTRL" Key="\'" Command="{Binding MyCommand}"/>
<KeyBinding Modifiers="CTRL" Key="&apos;" Command="{Binding MyCommand}"/>
<KeyBinding Gesture="CTRL+'" Command="{Binding MyCommand}"/>
<KeyBinding Gesture="CTRL+&apos;" Command="{Binding MyCommand}"/>
<KeyBinding Gesture="CTRL+\'" Command="{Binding MyCommand}"/>

So how can this key combination be achieved?

ifinlay
  • 621
  • 1
  • 7
  • 24

2 Answers2

1

An apostrophe is not a key. It's a character that is eventually mapped to a key depending on the input device. OemQuestion works on my keyboard:

<KeyBinding Modifiers="CTRL" Key="OemQuestion"  Command="{Binding MyCommand}"/>

...but you may be better off handling the PreviewTextInput event if you really want to detect when an apostrophe is typed in:

How to detect when (forward) slash key is pressed in OEM keys C#

mm8
  • 163,881
  • 10
  • 57
  • 88
  • OemQuestion doesn't work on my keyboard but, as you say, it needs handling via a keystroke event of some kind. I've added a handler to the PreviewTextInput event on the datagrid where the keystroke needs handling but it's not firing for some reason. Nomatter, I get the principle and I'll work it out. Thanks for your input. – ifinlay Dec 19 '19 at 16:31
0

The key code for apostrophe is OemQuotes. This syntax should do the trick

   <KeyBinding Command="{Binding Command}"
          Modifiers="CTRL" Key="OemQuotes" />
zaphod-ii
  • 424
  • 3
  • 11
  • That compiles but the command doesn't fire. The Oem part makes me think it may relate to a niche keyboard of some kind. – ifinlay Dec 17 '19 at 19:28
  • I noticed that in the Key type converter, (System.Windows.Input.KeyConverter), they are using the "QUOTES" key token. I replaced "OemQuotes" with "QUOTES" and it seems to be working. – zaphod-ii Dec 17 '19 at 19:45
  • QUOTES isn't an option for the Key parameter. VS gives you a dropdown of all the available values and that's not one of them. I also tried using Gesture="CTRL+QUOTES" and "CTRL+QUOTE" but no joy. – ifinlay Dec 17 '19 at 19:50
  • Have you checked what key code is received, when ' key is pressed, in the callback of KeyDown event on your keyboard? Both Gesture="CTRL+QUOTES" and Gesture="CTRL" Key="Quotes" are working fine on my side. – zaphod-ii Dec 17 '19 at 19:54