user3911053
user3911053

Reputation:

Windows 8 KeyBinding

In Windows Desktop applications you can create a keyboard shortcut for the application (e.g. Escape to exit) using RoutedCommands, CommandBindings, and KeyBindings. But I cannot find any way to do this with Windows 8 and 8.1 metro apps.

Upvotes: 0

Views: 467

Answers (1)

Abdallah Shakhatreh
Abdallah Shakhatreh

Reputation: 770

You can use AutomationProperties.AccessKey or AutomationProperties.AcceleratorKey (non-mnemonic shortcut keys) to document access keys, this information passed to users via assistive technologies.

What you really should do is to use KeyDown or KeyUp events, According to MSDN :

Important Setting AutomationProperties.AcceleratorKey or AutomationProperties.AccessKey doesn't enable keyboard functionality. It only reports to the UI Automation framework what keys should be used, so that such information can be passed on to users via assistive technologies. The implementation for key handling still needs to be done in code, not XAML. You will still need to attach handlers for KeyDown or KeyUp events on the relevant control in order to actually implement the keyboard shortcut behavior in your app.

Try this (e.g Ctrl + Q to Close Application ) :

XAML :

<Grid  KeyDown="Grid_KeyDown" KeyUp="Grid_KeyUp">
    <Button Content="Exit" AutomationProperties.AcceleratorKey="Control Q" />
</Grid>

Code :

public bool isCtrlKeyPressed { get; set; }

private void Grid_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == VirtualKey.Control) isCtrlKeyPressed = true;
    else if (isCtrlKeyPressed && e.Key == VirtualKey.Q)
    {
        Application.Current.Exit();
    }
}

private void Grid_KeyUp(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == VirtualKey.Control) isCtrlKeyPressed = false;
}

Upvotes: 2

Related Questions