设置WPF中承载的Windows窗体元素的焦点

设置WPF中承载的Windows窗体元素的焦点,wpf,winforms,focus,Wpf,Winforms,Focus,我有一个带有TabControl的复杂WPF窗口。其中一个选项卡项承载WindowsFormsHost,它承载一些旧的Windows窗体控件 当我导航到此选项卡时,我尝试将焦点设置在其中一个控件上。 Keyboard.Focus()不工作,因为它需要IIInputElement,而旧的windows窗体控件不支持IIInputElement。因此,我调用旧Windows窗体控件本身的Focus()方法,但由于某些原因,它不起作用 我将代码用于对您能想到的每个事件调用Focus(): TabCon

我有一个带有TabControl的复杂WPF窗口。其中一个选项卡项承载WindowsFormsHost,它承载一些旧的Windows窗体控件

当我导航到此选项卡时,我尝试将焦点设置在其中一个控件上。 Keyboard.Focus()不工作,因为它需要IIInputElement,而旧的windows窗体控件不支持IIInputElement。因此,我调用旧Windows窗体控件本身的Focus()方法,但由于某些原因,它不起作用

我将代码用于对您能想到的每个事件调用Focus():

  • TabControl的SelectionChanged事件
  • TabItem的IsVisibleChanged事件
  • TabItem的GotFocus事件
  • 它们都不起作用。有人有什么想法吗

    谢谢

    我的解决方案:

    private void TabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
    {
        Dispatcher.BeginInvoke(() =>
            {
                FormsControl.Focus();
                System.Windows.Input.Keyboard.Focus(ControlHost);
                Dispatcher.BeginInvoke(() => FormsControl.Focus());
            });          
    }
    
    public static class DispatcherExtensions
    {
        /// <summary>
        /// Executes the specified delegate asynchronously on the thread the System.Windows.Threading.Dispatcher is associated with.
        /// </summary>
        /// <param name="dispatcher">System.Windows.Threading.Dispatcher</param>
        /// <param name="a">A delegate to a method that takes no arguments and does not return a value, which is pushed onto the System.Windows.Threading.Dispatcher event queue.</param>
        /// <returns>An object, which is returned immediately after Overload:System.Windows.Threading.Dispatcher.BeginInvoke is called, that represents the operation that has been posted to the System.Windows.Threading.Dispatcher queue.</returns>
        public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action a)
        {
            return dispatcher.BeginInvoke(a, null);
        }
    }
    
    private void tab control\u SelectionChanged(对象发送方,System.Windows.Controls.SelectionChangedEventArgs e)
    {
    Dispatcher.BeginInvoke(()=>
    {
    FormsControl.Focus();
    System.Windows.Input.Keyboard.Focus(控制主机);
    Dispatcher.BeginInvoke(()=>FormsControl.Focus());
    });          
    }
    公共静态类DispatcherExtensions
    {
    /// 
    ///在System.Windows.Threading.Dispatcher关联的线程上异步执行指定的委托。
    /// 
    ///System.Windows.Threading.Dispatcher
    ///对方法的委托,该方法不带参数且不返回值,该值被推送到System.Windows.Threading.Dispatcher事件队列中。
    ///调用一个在重载后立即返回的对象:System.Windows.Threading.Dispatcher.BeginInvoke,该对象表示已发布到System.Windows.Threading.Dispatcher队列的操作。
    公共静态DispatcherOperation BeginInvoke(此Dispatcher,操作a)
    {
    返回dispatcher.BeginInvoke(a,null);
    }
    }