mgottschild
mgottschild

Reputation: 1125

KeyUp event after TextBox is already updated

Consider this basic TextBox in WPF:

<TextBox Name="textBox1" KeyUp="textBox1_KeyUp" />

And the event:

using System.Diagnostics;
...
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{ Debug.WriteLine(textBox1.Text + "; " + e.Key.ToString()); }

If I type slow in the TextBox the output is:

t; T
te; E
tes; S
test; T

But if I type fast, the output is wrong (note the S already in textBox1.Text when processing key E):

t; T
tes; E
test; S
test; T

I want to process the correct e.Key (the last pressed). It seems to me that the event is not updated as fast as the TextBox.Text property. Is there a way to solve this problem?

Upvotes: 3

Views: 2289

Answers (1)

JaredPar
JaredPar

Reputation: 754665

The reason you see this behavior is because the contents of the TextBox are updated shortly after the KeyDown event occurs. When typing very fast it's possible to do it in the following order

  • KeyDown: T
  • KeyUp: T
  • KeyDown: E
  • KeyDown: S
  • KeyUp: E
  • KeyUp: S

If you want to process the last key which was pressed down in the KeyUp event you would have to listen to KeyDown and store the value somewhere between the events. I wouldn't recomend that though as you can get key events in many orders you wouldn't expect (especially on non-English keyboards). I would stick with handling the event in KeyDown or KeyUp.

Upvotes: 5

Related Questions