开发者

C# KeyPressEvents handled

I'm using a textbox that I want to only allow numbers and I found that this statement works.

e.Handled = !char.IsDigit(e.KeyChar开发者_如何学Python) && !char.IsControl(e.KeyChar);

But why is it !char.IsDigit() and not char.IsDigit()? Why is it negated? Shouldn't it be that if I enter a number, IsDigits returns true and that is what I want?


What this code is doing is saying if there is not a digit pressed and it is not a control character mark the event as handled so that further processing cannot occur.

So if a digit is pressed handled is set to false so the event passes on through and allows the normal processing logic of the keypress to occur.

As a clarification, see Edwin de Konning comments, setting Handled to True will prevent the keypresses from occuring as they mark the event as already handled. This is why the operations are a not.

The statement is logically equivalent to:

e.Handled = !(char.IsDigit(e.KeyChar) || !char.IsControl(e.KeyChar))

So if the character is either a digit or a control character (e.g. Ctrl+C) don't handle the event.

This is not good enough, however, to prevent non numeric characters from being entered, because cut and paste will still work. As Edwin de Konnig suggested, you may want to look at MaskedEdit


When intercepting key presses setting e.Handled to true tells the framework that the event was already handled and it must not do anything on behalf of this key press. By marking all unwanted key presses as handled, you are effectively filtering these events, leaving only the keys you want to see.


It is actually !char.IsDigit() And Also !char.IsControl(). So it will ignore your input if the character is a digit And Also a control character. I am not sure if that is actually what you want (They even are mutually exclusive, as Bob Vale stated). Perhaps you should also look into the use of a MaskedTextBox.


You should look what e.Handled doing...when you set it to true char wont be entered in texbox.


Lets break this down.

Say we hit 1 on the keyboard, what exactly is happening.

  • !char.IsDigit(1) == fasle so the whole will automatically be false, because when we use && if the first check is false then the whole statement becomes false.

Now if we look at e.Handled we see that if the value assign is false then we allow the value to be written to the Textbox where if the value was true then the value wouldn't be accepted.


The above method helps in removing inputs made by using control keys like Shift, so that you avoid, cased alphabets and special symbols.

While you punch in numbers from the keyboard there is no control key pressed and so the resultant is false allowing the input of the number. (you cannot input a number with a control key)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜