如何以编程方式隐藏 UWP 应用程序的键盘?

How to hide UWP application's keyboard programmatically?

在我的 UWP (Xamarin Forms) 应用程序中,我有一个条形码扫描器,每次扫描都会将文本填充到条目中。问题是,在我进行扫描后,键盘会随着条目的聚焦而弹出。

我想知道是否有一种方法可以隐藏软键盘,而不必绑定到条目的 FOCUSED 属性 以手动将条目设置为未聚焦状态。有没有办法让 OS 隐藏键盘?我不确定这是否可行。

您需要创建依赖服务并监听键盘出现时调用的事件。您可以像这样设置依赖服务:

IKeyboard.cs(在您的 PCL 项目中):

public interface IKeyboard
{
    event EventHandler<EventArgs> KeyboardShowing;
    event EventHandler<EventArgs> KeyboardHiding;
    void HideKeyboard();
}

Keyboard_UWP.cs(在您的 UWP 项目中):

public class Keyboard_UWP : IKeyboard
{
    private InputPane _inputPane;
    public event EventHandler<double> KeyboardShowing;
    public event EventHandler<EventArgs> KeyboardHiding;

    public KeyboardVisibility_UWP()
    {
        _inputPane = InputPane.GetForCurrentView();
        _inputPane.Showing += OnInputPaneShowing;
        _inputPane.Hiding += OnInputPaneHiding;
    }

    private void OnInputPaneShowing(InputPane sender, InputPaneVisibilityEventArgs args)
    {
        KeyboardShowing?.Invoke(this, null);
    }

    private void OnInputPaneHiding(InputPane sender, InputPaneVisibilityEventArgs args)
    {
        KeyboardHiding?.Invoke(this, null);
    }

    public void HideKeyboard()
    {
        _inputPane.TryHide();
    }
}

然后在你的PCL中,你可以在播放时收听:

DependencyService.Get<IKeyboard>().KeyboardShowing += OnKeyboardShowing();

private void OnKeyboardShowing(object sender, EventArgs e)
{
    if (you want to hide the keyboard)
        DependencyService.Get<IKeyboard>().HideKeyboard();
}