0

The goal is simple: When the user enters chars in a textbox, I want to detect if this char is the question mark key (?). I don't care what to use (text changed, key down etc...) One thing to mention: I am working on a german keyboard layout and therefore I need a solution independent from the keyboard (for example: e.Key = Keys.OemQuestion isn't working, it fires when I press the plus (+) key)

Edit: I tried Convert.toString((char)e.Key) which returned \u0095 and e.Key.ToString() which returned OemOpenBrackets

Shmosi
  • 322
  • 2
  • 17
  • `textBox1_KeyPress(object sender, KeyPressEventArgs e)`..`if (e.KeyChar == '?') {...}`? – Dmitry Bychenko Dec 25 '17 at 14:02
  • 1
    If you want it independent from the keyboard, why are you checking `e.Key` instead of `e.KeyChar`? – Camilo Terevinto Dec 25 '17 at 14:02
  • @DmitryBychenko I am working in WPF so I have no KeyPress, but I used similar code with (char)e.Key, but I get as a result not '?' but '\u0095' – Shmosi Dec 25 '17 at 14:33
  • @CamiloTerevinto I am working in WPF and have no e.KeyChar option (as far as i know/researched) – Shmosi Dec 25 '17 at 14:36
  • https://stackoverflow.com/questions/13587270/keypress-event-equivalent-in-wpf – Dmitry Bychenko Dec 25 '17 at 14:41
  • You are using the wrong event. KeyDown tells you only about virtual keys, the question mark does not have a dedicated key like F1 does. Virtual keys are the same anywhere in the world, the character they produce when pressed is not. They depend on the active keyboard layout. You want to be notified about characters, not keys. In WPF use the TextInput event. Location still matters btw, a Greek user will type ";" for a question mark, a Spanish user will write one upside-down at the start of the sentence :) – Hans Passant Dec 25 '17 at 15:22
  • @HansPassant I tried it with the textchanged, but it is kinda messy and I was hoping for a better solution – Shmosi Dec 30 '17 at 12:03
  • You chose the worse solution. A *lot* worse. Use the correct one. – Hans Passant Dec 30 '17 at 12:08
  • I used the textinput event (didn't know this existed...) and managed to detect the entered keys (solution as answer down below) – Shmosi Dec 31 '17 at 12:28

1 Answers1

0

I chose the solution from @HansPassant and managed to do it with the TextInput event.

First in the constructor:

InitializeComponent();
CommandTextBox.AddHandler(TextBox.TextInputEvent, new TextCompositionEventHandler(CommandTextBox_TextInput), true);

You need this code to actually fire the event

in TextInput

if(e.Text == "?")
{
     //Do something
}

NOTE: This does not capture space, control, shift etc.

Shmosi
  • 322
  • 2
  • 17