I want to suppress a key stroke in a TextBox. To suppress all keystrokes other than Backspace, I use the following:
private void KeyBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
e.Handled = true;
}
However, I only want to suppress keystrokes when the key pressed was Backspace. I use the following:
if (e.Key == System.Windows.Input.Key.Back)
{
e.Handled = true;
}
However, this does not work. The character behind the selection start is still deleted. I do get "TRUE" in the output, so the Back key is being recognized. How would I prevent the user from pressing backspace? (My reason for this is that I want to delete words instead of characters in some cases, and so I need to handle the back key press myself).)
Just set e.SuppressKeyPress = true (in KeyDown event) when you want to suppress a keystroke. Ex, prevent backspace key change your text in textbox using the following code:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
e.SuppressKeyPress = true;
}
}