[Code] Handling Backspace Key in WP7

I just came across a question on Stackoverflow asking how to handle the backspace key in a textbox. This isn’t something I’ve had to do, but my initial reaction would’ve been to handle it as with any other button. Simply, handle the textbox’s OnKeyDown event and then check the event argument to see if the relevant key has been pressed. For example, if we wanted to see if the ‘Enter’ key had been pressed whilst the textbox has focus, we could do this:

private void myTextBox_KeyDown(object sender, KeyEventArgs e) 
  if(e.Key == Key.Enter) 
 MessageBox.Show("Enter key has been pressed"); 

This works fine for any button except the backspace button since it’s a little different from the other characters on the keyboard. The textbox control internally handles the backspace action and removes a letter from the textbox. Once the letter is removed, the event is no longer bubbled up to the OnKeyDown event and so you can’t handle it. If there are no letters in the textbox, then the control doesn’t remove any letters and the event is forwarded to the OnKeyDown event. Therefore, in order to see if the backspace button is pressed, we need to use the AddHandler method. This method shouldn’t be overused, but it’s well suited for this problem.

To ensure that the page is entirely loaded, we going to handle the page’s Loaded event:

 public MainPage()
     this.Loaded += new RoutedEventHandler(MainPage_Loaded);

Within the event, we use our AddHandler method:

 void MainPage_Loaded(object sender, RoutedEventArgs e)
     myTextBox.AddHandler(TextBox.KeyDownEvent, new KeyEventHandler(myTextBox_KeyDown), true);

We can then handle our event as normal, using Key.Back as the property to check against:

 private void myTextBox_KeyDown(object sender, KeyEventArgs e)
 if(e.Key == Key.Back)
 MessageBox.Show("Backspace key has been pressed");

You should now be able to handle the backspace key, even if the textbox already has text in it.

Hope that’s useful!



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: