A greate Windows App requires not only mouse and touch screen friendly, but also need to think about keyboards. Especially for some common short cuts, like Undo (CTRL + Z). So that the App can provide better user experience.
So how can we define short cut keys in UWP? Take my App Tracing as example, I need to implement short cuts for Undo (CTRL + Z). First, we need to consider which Control is being focused by the user currently. If we want the whole UI to respond to that short cut, then the Control will be the UI Control placed at the most outter node of the XAML
page, usually it is the Grid
.
First, let's find the first Grid
element under Page
, define 2 events on it: KeyDown
and KeyUp
<Grid Background="{ThemeResource TracingAcrylicBrush}" KeyDown="LayoutRoot_KeyDown" KeyUp="LayoutRoot_KeyUp">
Because the short cut we want to use is a combined key (CTRL + Z), so we need to know if the user has pressed Ctrl key already. So we need to define a bool
variable to check if Ctrl
key is being pressed.
private bool _isCtrlKeyPressed;
And then define the event handler:
private void LayoutRoot_KeyUp(object sender, KeyRoutedEventArgs e)
And
private async void LayoutRoot_KeyDown(object sender, KeyRoutedEventArgs e)
The parameter KeyRoutedEventArgs e
describes the information about which key the user is pressing, it is type of Windows.System.VirtualKey
enum. So to check if Ctrl key is pressed, just see if e.Key == VirtualKey.Control
. Now the logic to remember Ctrl key status is to set _isCtrlKeyPressed
to true when Ctrl key is pressed, and restore to false when user release the key
private void LayoutRoot_KeyUp(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Control) _isCtrlKeyPressed = false;
}
private async void LayoutRoot_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Control) _isCtrlKeyPressed = true;
}
Then, we need to check if Z key is pressed to finish the combined key. It is also handed in the LayoutRoot_KeyDown event handler, after check if Ctrl key is pressed, then check e.Key
is Z or not, like this:
private async void LayoutRoot_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Control) _isCtrlKeyPressed = true;
else if (_isCtrlKeyPressed)
{
switch (e.Key)
{
case VirtualKey.Z: ViewModel.CommandUndo.Execute(null); break;
}
}
}
Now, your application UI should be able to respond to CTRL+Z combined key short cut.
Simply, if you have other keys that can combined with Ctrl, just put them into swtich case statements like this:
case VirtualKey.V: await PasteInkOrImageFromClipboard(); break;
case VirtualKey.Z: ViewModel.CommandUndo.Execute(null); break;
case VirtualKey.Y: ViewModel.CommandRedo.Execute(null); break;
case VirtualKey.S: ViewModel.CommandSaveCurrent.Execute(null); break;
暗影吉他手
KeyDown响应不了Alt键……