Thursday, August 27, 2009

Capturing keyboard shortcut in Silverlight

Let's assume you have some Silverlight application and you want to do something when the user types Ctrl-M for example. It is actually quite simple. This works for User Controls in Silverlight also.

I have read that the key to this is to make sure your root layout element is a Canvas, not a Grid. However, I have not verified that it does NOT work with a Grid.

You Canvas just needs to be wired up to the key down event. Here is what that would look like.

<Canvas x:Name="LayoutRoot" KeyDown="LayoutRoot_KeyDown">…</Canvas>

Here is what the event handler C# snippet would look like.

private void LayoutRoot_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.M)
{
MessageBox.Show("Got Control-" + e.Key.ToString());
}

if (e.Key == Key.Escape)
{
MessageBox.Show("Got Escape");
}
}

I have found that you only get some key events. It seems loosely tied to if the browser implements the keystroke or not. Here are the ones that I know do NOT work: B, D, E, F, G, H, I, J, L, N, O, P, Q, R, S, T, W. The ones that do work are: A, C, K, M, U, V, X, Y, Z.

As you can see many of keystrokes are not usable with the control key (Ctrl). So, I recommend using something like Control-Shift (Ctrl-Shift). I have had much better luck with this. The syntax is a bit trickier, but it is fairly common with handling these types of events. Basically you have to compare Keyboard.Modifiers with the result of the bit operation. Just add your modifier keys as desired.

Here is an example of how to handle the Ctrl-Shift-S keystroke.

private void LayoutRoot_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.Modifiers == (ModifierKeys.Control | ModifierKeys.Shift) && e.Key == Key.S)
{
MessageBox.Show("Got Control-Shift" + e.Key.ToString());
}

if (e.Key == Key.Escape)
{
MessageBox.Show("Got Escape");
}
}

No comments: