WPF: Using a Virtual Keyboard

杀马特。学长 韩版系。学妹 提交于 2020-08-23 08:02:08

问题


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


回答1:


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

I would recommend you to go through these two tutorials:

  • A Software Virtual Keyboard for Your WPF Apps
  • A Touch Screen Keyboard Control in WPF

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;
}


来源:https://stackoverflow.com/questions/48911782/wpf-using-a-virtual-keyboard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!