开发者

c# handling keypresses

private void textBox1_KeyPress开发者_如何学Go(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar < '0' || e.KeyChar > '9')
        if (e.KeyChar != '\b')
            e.Handled = true;

}

i am not understanding how this code is not allowing anything except backspace and numbers.

  1. the first if statement is saying if it is not 0 - 9 then dont do anything?
  2. the second one is saying if it's not backspace dont do anything?
  3. what does e.Handled=True do?


The first if statement is basically saying if it is a digit, allow it to proceed as normal - otherwise go into the second if statement.

The second if statement is saying that if it's also not backspace, allow it to proceed as normal - otherwise go onto the assignment statement.

e.Handled = true; indicates that the event handler has already processed the event and dealt with it, so it doesn't need to be processed any further. In other words, please don't take any further action.

Here's an alternative way of writing the same body:

bool isDigit = e.KeyChar >= '0' && e.KeyChar <= '9';
bool isBackspace = e.KeyChar == '\b';

// If we get anything other than a digit or backspace, tell the rest of
// the event processing logic to ignore this event
if (!isDigit && !isBackspace)
{
    e.Handled = true;
}


1 and 2: It's actually the other way around. This is saying that "if the key is not 0-9, then check if it is backspace. If it is not backspace, then e.Handled is true."

3: When e.Handled is set to true the control, parent form, and whatever other thing listening to capture the key press will NOT do anything. e.Handled basically says, "It is taken care of, no one else worry about it."


What this code is doing is setting e.Handled=true when the character is

  • Not a number character
  • And not the backspace character
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜