0

I have a PreviewKeyDown event that I use to filter my input (I need to filter out spaces among other things, so using PreviewKeyPress is out).

It is all working fine, except it eats my Delete, Backspace, Home, Arrow, Page Up etc keypresses.

I can just try to think of all the keys that I think should be allowed and tell my event to ignore them:

if ((e.Key == Key.Up) || (e.Key == Key.Down) || (e.Key == Key.Left) 
    || (e.Key == Key.Right) || (e.Key == Key.Delete) || (e.Key == Key.Home) 
    || (e.Key == Key.End) || (e.Key == Key.PageUp) || (e.Key == Key.Insert) 
    || (e.Key == Key.F1))

But I am sure I will miss some.

Is there a better way that just making a huge "Or" statement and hoping I got them all?

leppie
  • 115,091
  • 17
  • 196
  • 297
Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • Can't you do the filtering in `KeyPress`? It's much easier when you can work on characters, not keys. – CodesInChaos Sep 17 '12 at 17:23
  • Btw there is no one-to-one mapping between keys and characters. Consider fun like dead-keys, shift state,... – CodesInChaos Sep 17 '12 at 17:25
  • @CodesInChaos - PreviewKeyPress does not receive spaces. (If you know a way to get PreviewKeyPress to get spaces then that would be GREAT!) – Vaccano Sep 17 '12 at 17:45
  • @CodesInChaos - I updated my question to be more clear about why I am not using PreviewKeyPress. – Vaccano Sep 17 '12 at 17:46
  • @CodesInChaos - I am using the solution given here: http://stackoverflow.com/a/10224883/16241 to convert my keys to chars. – Vaccano Sep 17 '12 at 17:48

2 Answers2

0

I'd do the filtering in KeyPress. At that point you'll deal with characters, and not with keys. So you don't need to care about most of them (AFAIR there are a handful of exceptions, such as return or backspace).

Use e.Handled to supress characters.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • Alas, PreviewKeyPress does not see spaces. I had it all in key press, but had to move my logic to KeyDown so I can catch spaces. – Vaccano Sep 17 '12 at 17:44
0

I am using this: How do you get the character appropriate for the given KeyDown event? to convert my key value to a char.

I realized that if the key is not a valid char, then it is being set to ASCII 32 (SPACE).

So I am just going to filter off of that....

// If this was not a true char then it will convert to the ASCII Space (#32).
// If this is not really a char, then we are done.
if ((newChar == (char)32) && (e.Key != Key.Space))
    return;
Community
  • 1
  • 1
Vaccano
  • 78,325
  • 149
  • 468
  • 850