WPF Key is digit or number

2020-04-02 07:49发布

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.

标签: c# wpf key keydown
6条回答
趁早两清
2楼-- · 2020-04-02 08:14

Add a reference to Microsoft.VisualBasic and use the VB IsNumeric function, combined with char.IsLetter().

查看更多
对你真心纯属浪费
3楼-- · 2020-04-02 08:15

Can you put some code to show what you intend? Shouldn't this work for you

      if(e.key.ToString().Length==1)

    `Char.IsLetter(e.key.ToString()[0])`
    else

//
查看更多
祖国的老花朵
4楼-- · 2020-04-02 08:33

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;
查看更多
三岁会撩人
5楼-- · 2020-04-02 08:35

In your specific case the answer provided by Jon and Jeffery is probably best, however if you need to test your string for some other letter/number logic then you can use the KeyConverter class to convert a System.Windows.Input.Key to a string

var strKey = new KeyConverter().ConvertToString(e.Key);

You'll still need to check to see if any modifier keys are being held down (Shift, Ctrl, and Alt), and it should also be noted that this only works for Letters and Numbers. Special characters (such as commas, quotes, etc) will get displayed the same as e.Key.ToString()

查看更多
Lonely孤独者°
6楼-- · 2020-04-02 08:39

try this, it works.

    private void txbNumber_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key >= Key.D0 && e.Key <= Key.D9) ; // it`s number
        else if (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) ; // it`s number
        else if (e.Key == Key.Escape || e.Key == Key.Tab || e.Key == Key.CapsLock || e.Key == Key.LeftShift || e.Key == Key.LeftCtrl ||
            e.Key == Key.LWin || e.Key == Key.LeftAlt || e.Key == Key.RightAlt || e.Key == Key.RightCtrl || e.Key == Key.RightShift ||
            e.Key == Key.Left || e.Key == Key.Up || e.Key == Key.Down || e.Key == Key.Right || e.Key == Key.Return || e.Key == Key.Delete ||
            e.Key == Key.System) ; // it`s a system key (add other key here if you want to allow)
        else
            e.Handled = true; // the key will sappressed
    }
查看更多
再贱就再见
7楼-- · 2020-04-02 08:41

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.

查看更多
登录 后发表回答