2

I've got a small event handler to process all keys pressed by the user or delivered by barcode scanner:

public void KeyDownSink(object sender, System.Windows.Input.KeyEventArgs e)
{
    _textRead.Append(e.Key);
}

private StringBuilder _textRead = new StringBuilder();


The variable _textRead should collect all characters pressed. I'm only interested in keys which produce a printable output (a-z,0-9, !"ยง$%& and so on). If the user presses e.g. Ctrl this will add the string LeftCtrl to _textRead, so I want to skip this key.

How to filter out control keys like Ctrl, Shift, , Alt... in an elegant way?

I know I can achieve this with a lot of conditional statements (if e.Key == Key.Ctrl) but I hope to find a nicer way.

Ronald McBean
  • 1,417
  • 2
  • 14
  • 27

2 Answers2

2

Try this:

using System;
using System.Text; 
using System.Windows.Input;

public void KeyDownSink(object sender, System.Windows.Input.KeyEventArgs e)   
{  
    string keyPressed = _keyConv.ConvertToString(e.Key);

    if (keyPressed != null && keyPressed.Length == 1) 
    {
        if (char.IsLetterOrDigit(keyPressed[0]))
        {
            _textRead.Append(keyPressed[0]);
        }
    }
}

private StringBuilder _textRead = new StringBuilder();   
private KeyConverter _keyConv = new KeyConverter();
nabulke
  • 11,025
  • 13
  • 65
  • 114
  • Just checked some more answers about this [topic](http://stackoverflow.com/a/5826175/913577). This gets way to complicated, I think I just stick with your solution. โ€“ Ronald McBean Dec 07 '11 at 13:48
0

I stumbled upon this questions for KeyEventArgs filtering. Since this is bold in the question I'd like to add the answer for that question

Filtering out modifiers

public void KeyDownSink(object sender, System.Windows.Input.KeyEventArgs e)  {
        var pressedModifiers = e.KeyboardDevice.Modifiers;
        if (pressedModifiers != ModifierKeys.None) return;

        //do your stuff
}

this will filter out combinations such as Ctrl+a

Filtering out specific modifiers

public void KeyDownSink(object sender, System.Windows.Input.KeyEventArgs e)  {
        List<Key> ExitKeys = new List<Key> { Key.LeftCtrl, Key.RightCtrl, Key.LeftAlt, Key.RightAlt, Key.LeftShift, Key.RightShift };
        if (ExitKeys.contains(e.Key)) return;

        //do your stuff
}
Jan
  • 3,825
  • 3
  • 31
  • 51