Search code examples
c#windows-phone-7windows-phonekeystrokebackspace

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


Solution

  • It's true that there is no easy way to handle this scenario, but it is possible.

    You need to create some member variables in the class to store the state of the input text, cursor position, and back key pressed status as we hop between the KeyDown, TextChanged, and KeyUp events.

    The code should look something like this:

        string m_TextBeforeTheChange;
        int m_CursorPosition = 0;
        bool m_BackPressed = false;
    
        private void KeyBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            m_TextBeforeTheChange = KeyBox.Text;
            m_BackPressed = (e.Key.Equals(System.Windows.Input.Key.Back)) ? true : false;
        }
    
        private void KeyBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (m_BackPressed)
            {
                m_CursorPosition = KeyBox.SelectionStart;
                KeyBox.Text = m_TextBeforeTheChange;
            }
        }
    
        private void KeyBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            KeyBox.SelectionStart = (m_BackPressed) ? m_CursorPosition + 1 : KeyBox.SelectionStart;
        }