开发者

Difficulty keychar

开发者 https://www.devze.com 2023-01-18 11:11 出处:网络
Why this recipe is wrong if (e.KeyChar <= (char)Keys.NumPad0 && e.KeyChar >= (char)Keys.Nu开发者_C百科mPad2)

Why this recipe is wrong

        if (e.KeyChar <= (char)Keys.NumPad0 && e.KeyChar >= (char)Keys.Nu开发者_C百科mPad2)
        {
            if (e.KeyChar <= (char)Keys.O && e.KeyChar >= (char)Keys.Oem2)
            {
                MessageBox.Show("Yes");
            }
        }

I want to be numbers between 0 and 2


You are checking that it's equal or less than 0 and at the same time equal or greater than 2. That's not possible. You have to switch your greater than to less than and and vice versa, and to handle both numpad and other numeric keys, change to this:

if (e.KeyChar >= (char)48 && e.KeyChar <= (char)50)
    ...


Keys.O

since you cannot start enum name with 0 (number zero) this must be O (letter o)

and whole logic seems flawed, it should be something like

 if ((e.KeyChar >= (char)Keys.NumPad0 && e.KeyChar <= (char)Keys.NumPad2) || (e.KeyChar => (char)Keys.Oem0 && e.KeyChar <= (char)Keys.Oem2))

(im not sure about >= and <= and Oem0)


I can't tell whether this code is present in a KeyDown or KeyPress event handler. If you want to filter typing keys then you should use KeyPress. And the code is then simply:

        if (e.KeyChar >= '0' && e.KeyChar <= '2') {
            MessageBox.Show("yes");
        }


Between 0 and 2 ...

e.KeyChar >= (char)Keys.NumPad0 && e.KeyChar <= (char)Keys.NumPad2
0

精彩评论

暂无评论...
验证码 换一张
取 消