Capturing Text Input focus in WPF using Browser Control in WinFormsHost
Well That was a mouthful.
So you’re making a touch screen, no keyboard app with WPF, GREAT! Why? Who cares. You're doing it. First things first, you need a WinForms Control in your XAML. But why Erik? I'm using WPF? Because WinForms lets you hook into all the DOM goodies we want.
And you know that you have to trick the registry into using IE 11 right? Ok good...
Moving on. Stick a browser in your XAML.
<WindowsFormsHost Name="WebView"> <wf:WebBrowser/> </WindowsFormsHost>
Now the fun part. Below is the code needed to hook into the javascript events thrown by the browser engine as it’s handling input. You don’t need all those events, but it gives you an idea of what to play with. If you are on a Tablet, this is a good time to show the virtual keyboard. This code is pretty simple, when you load the page, walk the DOM, find all the places you want to catch for text input or whatever. Then attach it. Done.
private void LoadCompleteEventHandler(object sender, WebBrowserDocumentCompletedEventArgs navigationEventArgs) { var htmlDocument = WebView.Document; if (htmlDocument != null) { HtmlElementCollection elements = htmlDocument.GetElementsByTagName("input"); foreach (HtmlElement elem in elements) { elem.AttachEventHandler("onselectionchange", FocusStart); elem.AttachEventHandler("onchange", FocusStart); elem.AttachEventHandler("focus", FocusStart); elem.AttachEventHandler("focusevent", FocusStart); elem.AttachEventHandler("onfocus", FocusStart); elem.AttachEventHandler("onclick", (sender1, e1) => FocusStart(elem, EventArgs.Empty)); } } } private void FocusStart(object sender, EventArgs e) { System.Windows.MessageBox.Show("FocusStart"); _kbHelper.ShowTouchKeyboard(true, false); }













