Thursday, November 13, 2008

Capturing Control Key Sequences in Silverlight 2

It took me a while to locate this, but I found in this MSDN article how to capture control key sequences in Silverlight 2. I was expecting to be able to 'and' the control key with the pressed alpha key, but that's not the way it works. I attached the following event handler to my layout root grid's KeyUp event. This performs a 'save' when pressing Ctrl+S, and 'save and close' when pressing Ctrl+Shift+S:

        /// <summary>
        /// Handles keyboard shortcuts.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void LayoutRoot_KeyUp(object sender, KeyEventArgs e)
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                switch (e.Key)
                    case Key.S:
                        // Ctrl+S: save; Ctrl+Shift+S: save and close
                        e.Handled = true;
                        SaveMyItem((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift);

1 comment: