Cancelling keyevents

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a textbox that should allow only numeric input. I have no problem capturing invalid keys but how do I cancel a keyevent? I want to block the input of e.g. any letter, but all of the key properties I find are read-only

Thanks
 
I have worked out a simple solution for those who might be searching

private void txtProject_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
int keyChar = (int)e.KeyChar
// Allow '0..9' and '.' and Backspace
if ((keyChar < 48 || keyChar > 57) && keyChar != 46 && keyChar != 8) e.Handled = true
}// txtProject_KeyPres
 
Tom said:
I have worked out a simple solution for those who might be searching:

private void txtProject_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) {
int keyChar = (int)e.KeyChar;
// Allow '0..9' and '.' and Backspace.
if ((keyChar < 48 || keyChar > 57) && keyChar != 46 && keyChar != 8) e.Handled = true;
}// txtProject_KeyPress

FYI, you can also write this a bit cleaner:

private void textBox1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != '.' &&
e.KeyChar != '\b';
}
 
Back
Top