3
I created an example Winform C# . net containing textbox1
, textbox2
and button1
to simulate the following situation:
When starting the application, the textbox1
gets the focus and when we press Enter, your event was scheduled KeyDown
so that the focus goes to the textbox2
.
It also happens that within it KeyDown
of textbox1
some kind of processing must be performed, which in my example is represented by a Thread.Slepp(5000)
.
The problem occurs when we press several times the Enter in the textbox1
. It performs several times the processing of this KeyDown
when it was expected that textbox1
and focus on the textbox2
.
Apparently it stores some kind of buffer keyboard, firing several times the event of the textbox
selected.
any suggestions as to how such a situation might be dealt with, so that once the textbox1
has the focus regardless of how many times it is pressed Enter, he perform only once the event KeyDown
and focus on the textbox2
?
Code used for example:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Thread.Sleep(5000);
SendKeys.Send("{TAB}");
}
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
Thread.Sleep(5000);
SendKeys.Send("{TAB}");
}
}
}
Have you ever tried to put the following line
textbox2.Focus();
instead ofSendKeys.Send("{TAB}");
? Maybe it works.– Érik Thiago
Yes @Érikthiago, the problem is the various executions of Keydown of textbox1. Another situation is also that this was just an example, and I will not know what will be the next component to receive the focus, the use of
SendKeys.Send("{TAB}")
leaves it to the application by Tabindex, thus being mandatory.– Murilo Fechio
Place
SendKeys.Send("{TAB}");
beforeThread.Sleep(5000);
– ramaral
He continues with the "buffer of Enter" and so he executes
SendKeys.Send("{TAB}");
andThread.Sleep(5000);
several times, both of the textbox1 how much of textbox2– Murilo Fechio
Yes will continue with buffer, but you should be running textbox1 once and then jump to textbox2, right?
– ramaral
Yeah, except by jumping into the textbox2, as we have several Enter in the buffer he executes the Keydown of textbox2 also, and several times, soon the focus does not necessarily stay on the desired textbox.
– Murilo Fechio
Yes, but that’s the expected behavior. Maybe there’s a possibility to get around that but it’s not much "beautiful". I’ll put an answer for you to test.
– ramaral
On second thought I see no way to distinguish one enter which must be accepted by one or more others who must not be accepted.
– ramaral