KeyDown Event + Enter. Clear keyboard buffer

3

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

When you start the application, the textbox1 gets the focus and when we press Enter , its KeyDown event has been programmed so that the focus moves to textbox2 .

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

The problem occurs when we press Enter several times in textbox1 . It performs several times the processing of this KeyDown when it was expected to be executed from textbox1 and passed the focus to textbox2 .

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

Any suggestion of how this type of situation can be handled, so that once textbox1 has focus regardless of how many times Enter is pressed, it only runs once event KeyDown and focus on textbox2 ?

Sample used code:

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}");                    
        }           
    }
}
    
asked by anonymous 30.04.2015 / 14:13

2 answers

1

Because you do not try to encapsulate as objects, you put the sendKeys.send("{TAB}") and Thread.Sleep as properties of each textbox .

In this way you can call the event independently, at any time and in whatever order you like.

    
16.05.2016 / 15:41
0

Why not just put a control variable? Something like:

int ok1 = 0;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{

    if (e.KeyCode == Keys.Enter)
    {
        if (ok1 > 0) return;
        ok1++;
        Thread.Sleep(5000);
        SendKeys.Send("{TAB}");
        ok2 = 0;
    }
}

int ok2 = 0;
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{

    if (e.KeyCode == Keys.Enter)
    {
        if (ok2 > 0)
        {
            return;
        }
        ok2++;
        Thread.Sleep(5000);
        SendKeys.Send("{TAB}");
        ok1 = 0;
    }
}
    
22.08.2016 / 23:37