Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Key is digit or number

Tags:

c#

key

wpf

keydown

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.

like image 639
user13657 Avatar asked Feb 12 '13 13:02

user13657


2 Answers

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.

like image 95
Jon Avatar answered Nov 10 '22 12:11

Jon


e.Key is giving you a member of the enum System.Windows.Input.Key

You should be able to do the following to determine whether it is a letter or a number:

var isNumber = e.Key >= Key.D0 && e.Key <= Key.D9;
var isLetter = e.Key >= Key.A && e.Key <= Key.Z;
like image 11
Khan Avatar answered Nov 10 '22 12:11

Khan