In my WPF app I am using what's written below to bind a key press of the F10 key to running a method in my script named 'btn_font_click'. However obviously UWP does not support direct keybindings like this in XAML since it's universal and not designed for Windows.
Is there any way that I can get this same effect in a UWP application?
<Window.Resources>
<RoutedUICommand x:Key="cmd1"></RoutedUICommand>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource cmd1}"
Executed="btn_font_Click">
</CommandBinding>
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Key="F10" Command="{StaticResource cmd1}"></KeyBinding>
</Window.InputBindings>
I'm using for inputting data from an RFID reader. Currently when the RFID card is scanned it presses F10, types out its data and then presses enter. My idea is F10 sets the keyboards focus to a textbox, the script then waits for an enter press while the RFID types out its data and it then takes what's in the text box and splits it into an array for usage within the app.
If there's a better or more direct way for getting the data from within the RFID card to my array I'm open for other potential solutions.
Edit: After looking into this for a while I've found that a 'Keyboard Accelerator' would be best for this programs current functionality as I would like the RFID card to still work while the app isn't in focus. Could I get some pointers as of how to set up a Keyboard Accelerator linking an F10 key press to running my method?
If you want to set up this kind of application-wide keyboard shortcut mechanism, activators are definitely one way to go about doing it.
There is a documentation on keyboard accelerators available and this functionality is available since the Fall Creators Update. Each UIElement
has a KeyboardAccelerators
collection, which allows you to define keyboard accelerators which interact with it. In case of buttons and menu items invoking the specified shortcut automatically invokes the control, but to make your TextBox
focused, you have to specify this behavior yourself using the Invoked
event:
<TextBox>
<TextBox.KeyboardAccelerators>
<KeyboardAccelerator Modifiers="None"
Key="F10" Invoked="KeyboardAccelerator_OnInvoked" />
</TextBox.KeyboardAccelerators>
</TextBox>
And in the event handler the TextBox
is then focused:
private void KeyboardAccelerator_OnInvoked(
KeyboardAccelerator sender,
KeyboardAcceleratorInvokedEventArgs args )
{
(args.Element as Control).Focus(FocusState.Keyboard);
}
The KeyboardAcceleratorInvokedEventArgs.Element
property contains a reference to our TextBox
, I cast it to Control
, as this is the parent of TextBox
that declares the Focus
method and you can potentially reuse this method on any focusable control.