I have a WPF C# program where I attempt to delete certain characters from a text box at TextChanged event. Say, for instance, the dollar sign. Here is the code I use.

private void txtData_TextChanged(object sender, TextChangedEventArgs e)
{
   string data = txtData.Text;

   foreach( char c in txtData.Text.ToCharArray() )
   {
      if( c.ToString() == "$" )
      {
         data = data.Replace( c.ToString(), "" );
      }
   }
   
   txtData.Text = data;
}

The problem I have is that whenever the user enters $ sign (Shift + 4), at the TextChanged event it removes the $ character from the textbox text alright, but it also moves the cursor to the BEGINNING of the text box which is not my desired functionality.

As a workaround I thought of moving the cursor the the end of the text in the text box, but the problem there is that if the cursor was positioned at some middle position then it would not be very user friendly. Say, for instance the text in the textbox was 123ABC and if I had the cursor after 3, then moving the cursor to the end of the text would mean that at the next key stroke user would enter data after C, not after 3 which is the normal functionality.

Does anybody have an idea why this cursor shift happens?

It happens because you changed the text. I'd handle this by using this code:

Boolean shifted = false;

private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e) {
    if (e.Key == Key.LeftShift || e.Key == Key.RightShift) {
        shifted = true;
    } else if (shifted == true && e.Key == Key.D4) {
        e.Handled = true;
    }
}

private void textBox1_PreviewKeyUp(object sender, KeyEventArgs e) {
    if (e.Key == Key.LeftShift || e.Key == Key.RightShift) {
        shifted = false;
    }
}

It happens because you changed the text. I'd handle this by using this code:

Boolean shifted = false;

private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e) {
    if (e.Key == Key.LeftShift || e.Key == Key.RightShift) {
        shifted = true;
    } else if (shifted == true && e.Key == Key.D4) {
        e.Handled = true;
    }
}

private void textBox1_PreviewKeyUp(object sender, KeyEventArgs e) {
    if (e.Key == Key.LeftShift || e.Key == Key.RightShift) {
        shifted = false;
    }
}

Thanks for the quick reply!

I only showed you a part of a code, which in reality is used to capture the key events of a Barcode Reader. However if you use this method won't it still display text in the text box?

It will display everything but whatever you get when you press shift and the 4 key. Line 7 of the code says if a shift key is down and you pressed the 4 key, I've already handled this event (e.Handled = true) and you can ignore the event from then on.

Edited 5 Years Ago by Momerath: n/a

This article has been dead for over six months. Start a new discussion instead.