WPF Key is digit or number

给你一囗甜甜゛ 提交于 2019-12-01 14:03:22

问题


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.


回答1:


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.




回答2:


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;



回答3:


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()




回答4:


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
    }



回答5:


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




回答6:


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

//


来源:https://stackoverflow.com/questions/14834260/wpf-key-is-digit-or-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!