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?
The reason you see this behavior is because the contents of the
TextBoxare updated shortly after theKeyDownevent occurs. When typing very fast it’s possible to do it in the following orderIf you want to process the last key which was pressed down in the
KeyUpevent you would have to listen toKeyDownand 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 inKeyDownorKeyUp.