【问题标题】:Disable keyboard interaction with UWP app禁用与 UWP 应用的键盘交互
【发布时间】:2020-08-22 21:57:20
【问题描述】:

我正在构建一个 UWP 应用程序,我希望禁用与我的应用程序的键盘交互。这意味着当按下键盘上的任何键时,我的应用程序不应该以任何方式响应。

这可以实现吗?我可以选择性地禁用与 Tab 键等某些键的交互吗?

【问题讨论】:

    标签: c# uwp windows-10 win-universal-app windows-10-universal


    【解决方案1】:

    是的,您可以为此使用 KeyboardDeliveryInterceptor 类。有几点需要注意:

    1. 您需要在 appxmanifest 文件中声明受限功能“inputForegroundObservation”:
    <Capabilities>
      <Capability Name="internetClient" />
      <rescap:Capability xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" Name="inputForegroundObservation"/>
    </Capabilities>
    
    1. 您不能选择性地拦截键,但您可以响应代码中特定的拦截键并以所需的操作进行响应(例如,按下 Tab 键时移动焦点):
    KeyboardDeliveryInterceptor interceptor = KeyboardDeliveryInterceptor.GetForCurrentView();
    interceptor.IsInterceptionEnabledWhenInForeground = true;
    interceptor.KeyUp += delegate(KeyboardDeliveryInterceptor sender, KeyEventArgs args)
    {
        if (args.VirtualKey == Windows.System.VirtualKey.Tab)
        {
            // perform desired tab key action
        }
    };
    

    【讨论】:

    • 我的用例是禁用与 Tab 键的键盘交互并正常处理来自其余键的输入。因此,如果我按照您提到的方式使用 KeyboardDeliveryInterceptor 类拦截所有键,我可以以编程方式告诉我的应用程序正常处理来自所有其他键的输入吗?
    【解决方案2】:
    <Capabilities>
         <Capability Name="internetClient" />
         <rescap:Capability xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" Name="inputForegroundObservation"/>
    </Capabilities>
    

    按照 Stefan 上面所说的添加权限。添加权限后添加以下代码。

    Dispatcher.AcceleratorKeyActivated += Dispatcher_AcceleratorKeyActivated;
    
    private void Dispatcher_AcceleratorKeyActivated(CoreDispatcher sender, AcceleratorKeyEventArgs args)
        {
            if(args.key == Windows.System.VirtualKey.Tab)
            {
               args.Handled = true;
            }
        }
    

    以上代码阻止 Tab 按钮执行任何操作。因此,当用户按下 Tab 键时,不会执行任何操作。

    【讨论】:

      猜你喜欢
      • 2019-07-10
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多