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.

WinForms Control in WPF Window

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.




Back to DELEY'S Home Page