WPF Key is digit or number

user13657 picture user13657 · Feb 12, 2013 · Viewed 23.8k times · Source

I have previewKeyDown method in my window, and I'd like to know that pressed key is only A-Z letter or 1-0 number (without anyF1..12, enter, ctrl, alt etc - just letter or number).

I've tried Char.IsLetter, but i need to give the char, so e.key.ToString()[0] doesn't work, because it is almost everytime a letter.

Answer

Jon picture Jon · Feb 12, 2013

Something like this will do:

if ((e.Key >= Key.A && e.Key <= Key.Z) || (e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))

Of course you will also have to check that no modifier keys like CTRL are pressed according to your requirements.