【问题标题】:Setting the focus for a Windows Forms element hosted in WPF为 WPF 中托管的 Windows 窗体元素设置焦点
【发布时间】:2009-07-28 14:41:24
【问题描述】:

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

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

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

  1. TabControl 的 SelectionChanged 事件
  2. TabItem 的 IsVisibleChanged 事件
  3. TabItem 的 GotFocus 事件

它们都不起作用。有人有什么想法吗?

谢谢

【问题讨论】:

    标签: wpf winforms focus


    【解决方案1】:

    我的解决方案:

    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-11
      • 2011-09-17
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多