Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a backspace key stroke in a TextBox?

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).)

like image 850
msbg Avatar asked Mar 09 '13 21:03

msbg


People also ask

How do I turn off input Backspace?

Use onkeydown property and block key of backspace “8” or key “Backspace” to prevent users from using the backspace key in a textbox using JavaScript.

How do I change backspace key settings?

This is because you will have to set the backspace key to send backspace or delete. To do this, select the "Terminal" menu and choose "Setup" and select the "Keyboard" tab. Now choose the setting you wish in the "Backspace Key Sends" section. The key can send either Backspace or Delete.

How do I lock Backspace in word?

You can prevent this happening at all by disabling Overtype mode. Go to File, Options, Advanced and uncheck the “Use the Insert key to control overtype mode” option. This is also where, if the Insert key is not enabled, you can turn Overtype mode on and off.


2 Answers

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;
    }
}

Note that if you try this in the txtBox1_KeyUp() handler, it will not appear to work (because KeyDown already handled the event for the TextBox).

like image 167
Huy Nguyen Avatar answered Oct 19 '22 19:10

Huy Nguyen


In Silverlight, there is no way to handle system key events, such as backspace. Therefore, you can detect it, but not handle it manually.

like image 3
Den Delimarsky Avatar answered Oct 19 '22 20:10

Den Delimarsky