i have TextBox in my WinForm profram
How to prevent a user t开发者_开发百科yping all Characters Except arrow key, Esc and Enter ?
Sorry, i forgot to write this is for Windows-mobile and in Windows-mobile there isnt
e.SuppressKeyPress = true;
thanks, and sorry for the Non-understanding
The KeyDown event will do this for you.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
// These keys will be allowed
case Keys.Left:
case Keys.Right:
case Keys.Up:
case Keys.Down:
case Keys.Escape:
case Keys.Enter:
break;
// These keys will not be allowed
default:
e.SuppressKeyPress = true;
break;
}
}
You can handle event TextBox.KeyDown
.
There filter keys you do not want to pass through to the TextBox - check if KeyEventArgs.KeyCode is your code)
Then set KeyEventArgs.Handled and KeyEventArgs.SuppressKeyPress to true.
As BoltClock wrote those characters are not printable so you cannot 'type' them. If you meant to ignore these characters and do sth else for other characters, you can do that in the KeyDown
event of the textbox.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (
e.KeyCode == Keys.Left ||
e.KeyCode == Keys.Right ||
e.KeyCode == Keys.Down ||
e.KeyCode == Keys.Up ||
e.KeyCode == Keys.Enter ||
e.KeyCode == Keys.Escape
)
{
e.SuppressKeyPress = true;
return;
}
//do sth...
}
精彩评论