Search This Blog

Monday, November 28, 2011

Silverlight capturing key clicks; Silverlight capturing special key clicks; Silverlight Keyboard.Modifiers class

To capture special key clicks (like ctrl, alt and shift modifier key clicks) one does not have to use KeyDown & KeyUp method. There is a class Keyboard which is available in Silverlight as well. Use Keyboard.ModifierKeys to accomplish desired effect.

Sample usage:

if (Keyboard.Modifiers.Equals(System.Windows.Input.ModifierKeys.Control))
{
    //do something
}

Keyboard.ModifierKeys  allows a bitwise combination of its members.

To capture other key clicks one needs to write a static class which will be available in the whole application.

The example KeyPressMonitor class is available here.

3 comments:

  1. You can use:
    Application.Current.RootVisual.KeyDown;
    Application.Current.RootVisual.KeyUp;

    as well to catch key presses.

    ReplyDelete
  2. You can also write:

    if (((Keyboard.Modifiers & ModifierKeys.Control) > 0) && e.Key == Key.C)
    {

    }

    ReplyDelete
  3. Since .NET 4.0 there is a method HasFlag() available on enums which we can use to determine the clicked modifier key:

    if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
    {

    }

    ReplyDelete

If you like this post, please leave a comment :)