You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WinUI3触摸设备应用:如何阻止系统触摸键盘自动弹出?

解决WinUI3触摸设备自定义键盘场景下默认触摸键盘自动弹出的问题

方案1:通过InputPane主动隐藏系统键盘

利用WinUI3提供的InputPane类,在文本框获取焦点时手动隐藏系统触摸键盘:

using Windows.UI.ViewManagement;

private void CustomTextBox_GotFocus(object sender, RoutedEventArgs e)
{
    var inputPane = InputPane.GetForCurrentView();
    if (inputPane != null && inputPane.Visible)
    {
        inputPane.TryHide();
    }
}

注:此方法可能存在轻微延迟(系统键盘先弹出再隐藏),可结合其他方案优化体验。

方案2:自定义AutomationPeer彻底阻止触发逻辑

你之前使用的FrameworkElementAutomationPeer未屏蔽文本输入控件的自动化特性,需自定义Peer让系统识别为非输入控件:

using Windows.UI.Xaml.Automation.Peers;

public class NonInputAutomationPeer : FrameworkElementAutomationPeer
{
    public NonInputAutomationPeer(FrameworkElement owner) : base(owner)
    {
    }

    protected override object GetPatternCore(PatternInterface patternInterface)
    {
        // 不返回TextPattern,避免系统识别为文本输入控件
        if (patternInterface == PatternInterface.Text)
        {
            return null;
        }
        return base.GetPatternCore(patternInterface);
    }

    protected override AutomationControlType GetAutomationControlTypeCore()
    {
        // 将控件标记为自定义类型,进一步避免触发输入键盘逻辑
        return AutomationControlType.Custom;
    }
}

// 在自定义文本框中重写方法
protected override AutomationPeer OnCreateAutomationPeer()
{
    return new NonInputAutomationPeer(this);
}

此方法从自动化识别层面阻断系统键盘触发逻辑,无延迟问题。

方案3:通过XAML附加属性修改自动化元数据

无需编写C#代码,直接在XAML中设置控件的自动化属性,让系统不将其识别为文本输入控件:

<TextBox x:Name="CustomInputBox"
         AutomationProperties.AutomationControlType="Custom"
         AutomationProperties.IsKeyboardFocusable="False"/>

注:设置IsKeyboardFocusable="False"后,需手动处理控件的焦点逻辑,确保自定义键盘能正常响应输入。

额外说明

  • 以上方案均仅作用于当前应用,不会影响系统其他应用,无需修改注册表。
  • 若自定义控件需保留部分自动化特性,可按需调整AutomationPeer的重写逻辑,仅屏蔽触发键盘的关键模式即可。

内容的提问来源于stack exchange,提问作者Bevara Satyasairam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 06:32:36