Setting Focus to a WinForms Control Hosted in a WPF Window via WindowsFormsHost
Problem:
You have a WPF (Windows Presentation Foundation) Window and a WinForms
Control (System.Windows.Forms.Control) displayed in the WPF window using the
WindowsFormsHost
(System.Windows.Forms.Integration.WindowsFormsHost) adapter class.
And you'd like to set focus to the WinForms control.
It's not easy.

Solution:
private void SetFocus(System.Windows.Forms.Control control)
{
System.Windows.Forms.Integration.WindowsFormsHost windowsFormsHost = this.GetWindowsFormsHostContainer(control);
windowsFormsHost?.TabInto(new System.Windows.Input.TraversalRequest(System.Windows.Input.FocusNavigationDirection.First));
}
private WindowsFormsHost GetWindowsFormsHostContainer(System.Windows.Forms.Control control)
{
System.Windows.Forms.Control adapter = control.Parent;
System.Type adapterType = adapter.GetType();
if (adapterType.Name == "WinFormsAdapter")
{
System.Reflection.Assembly asm = typeof(System.Windows.Forms.Integration.WindowsFormsHost).Assembly;
Type type = asm.GetType("System.Windows.Forms.Integration.WinFormsAdapter");
object parent = type.InvokeMember(
"_host",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance,
null,
adapter,
new Object[] { });
System.Windows.Forms.Integration.WindowsFormsHost windowsFormsHost = parent as System.Windows.Forms.Integration.WindowsFormsHost;
return windowsFormsHost;
}
return null;
}
Reference:
I’d like to say I invented this myself but I didn’t; I found it via a lot of searching the internet and finding the Chinese article below, which was cited in a StackOverflow post.
- "Looking for the hard journey of WindowsFormsHost"
(Original Chinese)
http://www.cnblogs.com/notgg/archive/2009/11/25/1610333.html
(Google Translated to English)
http://translate.google.com/translate?js=n&sl=zh&tl=en&u=http://www.cnblogs.com/notgg/archive/2009/11/25/1610333.html - "Windows Forms and WPF Interoperability Input Architecture"
https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/windows-forms-and-wpf-interoperability-input-architecture
![]() |