c# – KeyDown + Enter event. Clear keyboard buffer

Question:

I created an example C# .net WinForm containing textbox1 , textbox2 and button1 to simulate the following situation:

When starting the application, textbox1 receives focus and when we press Enter , its KeyDown event has been programmed so that focus passes to textbox2 .

It also happens that within the same KeyDown of textbox1 some type of processing must be performed, which in my example is represented by a Thread.Slepp(5000) .

The problem occurs when we repeatedly press Enter on textbox1 . It runs the processing of this KeyDown several times when it was expected to run from textbox1 and pass focus to textbox2 .

Apparently it stores some kind of keyboard buffer , triggering the selected textbox event several times.

Any suggestions on how this kind of situation can be handled so that once textbox1 has focus, no matter how many times you press Enter , it only executes the KeyDown event once and passes focus to 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}");                    
        }           
    }
}

Answer:

Because you don't try to wrap as objects, you put sendKeys.send("{TAB}") and Thread.Sleep as properties of each textbox .

This way you will be able to call the event independently, at the time you want and in the order you want.

Scroll to Top
AllEscort