Convert received keys in PreviewKeyDown to a string

只谈情不闲聊 提交于 2019-12-04 17:44:46

Here is the event that I am using. The KeyDown gets the keys and the PreviewTextInput gets the actual text. So somewhere in between the keys are getting converted to text.

 public Window1()
            {
                InitializeComponent();
                TextCompositionManager.AddPreviewTextInputStartHandler(this, new TextCompositionEventHandler(Window_PreviewTextInput));
                this.AddHandler(Window.KeyDownEvent, new System.Windows.Input.KeyEventHandler(Window_KeyDown), true);
            }

    private void Window_PreviewTextInput(object sender, TextCompositionEventArgs e)
            {
            }

    private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
            {
            }

Key -> Text conversion is much more complicated than you think, there is actually no way to map a single key stroke to a single character because in some languages and some cases you need multiple keystrokes to compose a single character.

Since you are interested in input from a barcode scanner (that I assume will only generate a small subset of what windows can handle, maybe only ASCII maybe even less) you can build the conversion table yourself and hard code it into your program - it's much easier then to handle all the craziness that Windows text handling does (for fun, lookup "dead keys").

Gregory

Ok, stolen from this post.

[DllImport("user32.dll")]
static extern short VkKeyScan(char ch);

static public Key ResolveKey(char charToResolve)
{    
    return KeyInterop.KeyFromVirtualKey(VkKeyScan(charToResolve));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!