【发布时间】:2020-08-22 21:57:20
【问题描述】:
我正在构建一个 UWP 应用程序,我希望禁用与我的应用程序的键盘交互。这意味着当按下键盘上的任何键时,我的应用程序不应该以任何方式响应。
这可以实现吗?我可以选择性地禁用与 Tab 键等某些键的交互吗?
【问题讨论】:
标签: c# uwp windows-10 win-universal-app windows-10-universal
我正在构建一个 UWP 应用程序,我希望禁用与我的应用程序的键盘交互。这意味着当按下键盘上的任何键时,我的应用程序不应该以任何方式响应。
这可以实现吗?我可以选择性地禁用与 Tab 键等某些键的交互吗?
【问题讨论】:
标签: c# uwp windows-10 win-universal-app windows-10-universal
是的,您可以为此使用 KeyboardDeliveryInterceptor 类。有几点需要注意:
<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" Name="inputForegroundObservation"/>
</Capabilities>
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
}
};
【讨论】:
<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 键时,不会执行任何操作。
【讨论】: