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

.NET MAUI 6.0 Windows平板应用如何以编程方式调出虚拟键盘?

.NET MAUI 6.0 Windows 10平板:输入框获焦自动弹出虚拟键盘解决方案

问题背景

在Visual Studio 2022中开发基于.NET MAUI 6.0的Windows 10平板应用时,需要实现输入框获焦时自动弹出系统虚拟键盘,避免用户手动点击右下角键盘按钮。直接调用osk.exe存在两个问题:

  • 键盘作为独立应用弹出,会遮挡需要交互的输入框
  • 关闭键盘后应用返回时,输入框重新获焦导致osk.exe重复弹出

解决方案:使用Windows原生InputPane API

Windows平台提供了InputPane类(属于Windows.UI.ViewManagement命名空间),可以直接调用系统原生触摸键盘,完美解决上述问题:

  • 键盘弹出时系统会自动调整页面布局,不会遮挡输入框
  • 关闭键盘时输入框自动失焦,不会触发重复弹出
  • 完全集成在应用上下文内,无独立进程问题

方法1:直接在输入框事件中处理

  1. 在XAML中为输入框添加Focused和Unfocused事件:
<Entry x:Name="TargetEntry" Focused="Entry_Focused" Unfocused="Entry_Unfocused" />
  1. 在代码后台实现事件逻辑(仅针对Windows平台执行):
using Windows.UI.ViewManagement;

private void Entry_Focused(object sender, FocusEventArgs e)
{
    if (DeviceInfo.Platform == DevicePlatform.Windows)
    {
        InputPane.GetForCurrentView().TryShow();
    }
}

private void Entry_Unfocused(object sender, FocusEventArgs e)
{
    if (DeviceInfo.Platform == DevicePlatform.Windows)
    {
        InputPane.GetForCurrentView().TryHide();
    }
}

方法2:封装为可复用行为(推荐)

如果多个输入框需要该功能,可封装成Behavior实现复用:

  1. 创建行为类:
using Microsoft.Maui.Controls;
using Windows.UI.ViewManagement;

public class AutoShowKeyboardBehavior : Behavior<Entry>
{
    protected override void OnAttachedTo(Entry entry)
    {
        base.OnAttachedTo(entry);
        entry.Focused += OnEntryFocused;
        entry.Unfocused += OnEntryUnfocused;
    }

    protected override void OnDetachingFrom(Entry entry)
    {
        base.OnDetachingFrom(entry);
        entry.Focused -= OnEntryFocused;
        entry.Unfocused -= OnEntryUnfocused;
    }

    private void OnEntryFocused(object sender, FocusEventArgs e)
    {
        if (DeviceInfo.Platform == DevicePlatform.Windows)
        {
            InputPane.GetForCurrentView().TryShow();
        }
    }

    private void OnEntryUnfocused(object sender, FocusEventArgs e)
    {
        if (DeviceInfo.Platform == DevicePlatform.Windows)
        {
            InputPane.GetForCurrentView().TryHide();
        }
    }
}
  1. 在XAML中引用该行为:
<Entry Placeholder="输入内容">
    <Entry.Behaviors>
        <local:AutoShowKeyboardBehavior />
    </Entry.Behaviors>
</Entry>

注意事项

  • 确保项目目标框架为.NET 6.0,Windows平台配置正确
  • 测试时需在Windows 10平板模式下运行,或在系统设置中启用触摸键盘模拟
  • 避免同时使用osk.exe和InputPane方法,防止冲突

内容的提问来源于stack exchange,提问作者Joseph Foulk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 23:53:16