C# – WPF: Using a Virtual Keyboard

cwpfxaml

I have created a virtual keyboard user control to use across multiple windows within my application. I am wondering how I am able to get it to input into a textbox in a window when a key is pressed.

What I am looking for is something like:

private void keyboardKey_Click(object sender, RoutedEventArgs e){
var key = sender as Button;
textbox.Text += key.Content;
}

So for example, if I press the key for 'a', then 'a' is added to the textbox.

My mind tends towards some sort of binding property but as I am new to WPF, I have no idea where to begin. Something like

<local:QWERTYKeyboard TextboxBinding="TextboxName"/>

Thanks

Best Answer

This is quite complicated task. Fortunately there's couple good tutorials on this subject.

I would recommend you to go through these two tutorials:

Especially there first one should contain a sample app which should get you started.

For your particular question regarding getting the text into TextBox. One (naive) implementation is to track the focus.

Your virtual keyboard could have property which contains the currently focused TextBox:

public TextBox FocusedTextBox {get;set;}

And each of your app's textboxes could update the property based on the GotFocus-event:

private void txtBox_GotFocus(object sender, RoutedEventArgs e)
{
    // Set virtual keyboards' active textbox
    this.VirtualKeyboard.FocusedTextBox = txtBox;
}

Now in your Virtualkeyboard, when one presses "a", you can just update the content of the TextBox:

private void UserPressedVirtualKeyboard(object sender, RoutedEventArgs e)
{
    this.VirtualKeyboard.FocusedTextBox.Text = this.VirtualKeyboard.FocusedTextBox.Text + pressedChar;
}