【问题标题】:How to move the focus to next control using Tab key when a winform control is hosted in WPF?当 WPF 中托管 winform 控件时,如何使用 Tab 键将焦点移动到下一个控件?
【发布时间】:2018-10-05 12:07:49
【问题描述】:

我已将我的自定义 winform 控件托管到 WPF 项目中。我已经处理了自定义控件的 KeyDown 事件,以便在按下 Tab 或 Shift+Tab 键时导航到下一个控件。

这是我处理 Tab 键的代码,

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);

    if (e.Handled)
        return;

    if (this.AllowStandardTab)
    {
        Form form = this.FindForm();
        if (form != null)
        {
            if (e.KeyData == (Keys.Tab | Keys.Shift))
            {
                form.SelectNextControl(this, false, true, false, true);
                return;
            }
            else if (e.KeyData == Keys.Tab)
            {
                form.SelectNextControl(this, true, true, false, true);
                return;
            }
        }
    }
}

它在 winforms 中正常工作并导航到下一个控件。但它不适用于托管的 wpf 项目。

如何检测控件是否托管在 wpf 中,并在按下 Tab 键时将焦点移动到下一个 wpf 窗口?

【问题讨论】:

  • 也许您的控件会覆盖 IsInputKey 并始终为 Keys.Tab 返回 true?也许您应该根据您的 AllowStandardTab 状态在此处返回 true/false,以便进行默认处理。我怀疑 WFH 正确处理 ProcessDialogKey 而您的实现特定于 WF。当您的控件托管在 WPF 窗口中时,上面的表单将为空。

标签: c# wpf winforms


【解决方案1】:

默认情况下,它也可以使用 TAB 键在 WPF 中工作。控件是否真的来自winforms或WPF并不重要。这是我为您制作的简单示例。

<Window x:Class="StackPoC.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:StackPoC"
    mc:Ignorable="d"
    Loaded="Window_Loaded"
    Title="MainWindow" Height="450" Width="800">
<StackPanel>
    <TextBox Text="test x" />
    <TextBox Text="test y" />
    <TextBox Text="test z" />
    <TextBox Text="test w" />
    <Grid Name="containerForWinFormsControl" />
</StackPanel>

代码隐藏:

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Create the interop host control.
        System.Windows.Forms.Integration.WindowsFormsHost host =
            new System.Windows.Forms.Integration.WindowsFormsHost();

        // Create the MaskedTextBox control.
        MaskedTextBox mtbDate = new MaskedTextBox("00/00/0000");

        // Assign the MaskedTextBox control as the host control's child.
        host.Child = mtbDate;

        // Add the interop host control to the Grid
        // control's collection of child controls.
        this.containerForWinFormsControl.Children.Add(host);
    }

如果我正在考虑它无法在您的网站上运行的原因,我会想到一些事情。在进入您的 winforms 控件之前,必须在某处处理 TAB keydown 事件。我也不知道控件是否可聚焦,但无论如何你真的需要手动处理吗?框架确实关心我们这些事情。

【讨论】:

    猜你喜欢
    • 2012-09-04
    • 2014-06-30
    • 2011-11-12
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多