I am using the following textbox keypress() event to capture the keystrokes entered by user to restrict user to enter alphabet and numeric values.
private void textBoxName_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(char.IsLetter(e.KeyChar) ||
e.KeyChar == (char)Keys.Space ||
e.KeyChar == (char)Keys.Back ||
e.KeyChar==(char)Keys.ControlKey );
}
Now the problem is by using the above mentioned code I am not able to use shortcut keys like Ctrl+C or Ctrl+v even if keys.ControlKey is handled in the the keypress event.
What i am doing wrong here?
Thanks in advance.
The Keypress event is not raised if the Control key is pressed without any other key. Is used as a key modifier only. In this case, e.KeyChar
returns a modified value that char.IsLetter()
considers false
, the !
operator transforms it in true
and assigns it to e.Handled
, thus the keypress event is canceled.
to capture the keystrokes entered by user to restrict user to enter alphabet and numeric values.
If, as you said, numbers are part of the required input, char.IsLetterOrDigit()
should be used instead of char.IsLetter()
.
And punctuation? Is part of the input too?
These symbols are considered punctuation by char.IsPunctuation()
: \"%&/()?*@.,:;_-'
Two methods to have the same result.
In both, char.IsControl(e.KeyChar)
is used to check if Control is part of the Keycode and if it is, strip it by XOR(ing) it.
1) Filter using a simple regex. This one gives you more control on what to filter.
Regex _KeyFilter = new Regex(@"^[a-zA-Z0-9.,]");
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Back && e.KeyChar != (char)Keys.Return && e.KeyChar != (char)Keys.Space)
{
e.Handled = !_KeyFilter.IsMatch((char.IsControl(e.KeyChar)
? (char)(e.KeyChar ^ 64)
: e.KeyChar).ToString());
}
}
2) Filtert using char.IsLetterOrDigit()
and char.IsPunctuation()
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char)Keys.Back && e.KeyChar != (char)Keys.Return && e.KeyChar != (char)Keys.Space)
{
char _keypress = char.IsControl(e.KeyChar) ? (char)(e.KeyChar ^ 64) : e.KeyChar;
e.Handled = !char.IsLetterOrDigit(_keypress) && !char.IsPunctuation(_keypress);
}
}