Search code examples
c#timertextboxdelaysendkeys

Delay in Timer with 5 textboxes c#


I want to create something like an auto-typer.

I got 5 textboxes, and I am using a timer.

I would like to have a 5 second "pause/delay" between the text that is send from every textbox.

This is my Timer_Tick event:

private void Timer_Tick(object sender, EventArgs e)
    {
        if (txt1.Text != string.Empty)
        {
            SendKeys.Send(this.txt1.Text);
            SendKeys.Send("{ENTER}");
        }

        if (txt2.Text != string.Empty)
        {
            SendKeys.Send(this.txt2.Text);
            SendKeys.Send("{ENTER}");
        }

        if (txt3.Text != string.Empty)
        {
            SendKeys.Send(this.txt3.Text);
            SendKeys.Send("{ENTER}");
        }

        if (txt4.Text != string.Empty)
        {
            SendKeys.Send(this.txt4.Text);
            SendKeys.Send("{ENTER}");
        }

        if (txt5.Text != string.Empty)
        {
            SendKeys.Send(this.txt5.Text);
            SendKeys.Send("{ENTER}");
        }
    }

When I use timer.Interval = 5000, my application is sending every value of ALL textboxes every 5 seconds, but I want to have a delay of 5 seconds between every textbox.

Is this possible? I don't want to use System thread sleep, because the application will frozen..


Solution

  • make a global variable

    int time = 0;
    

    then your code can be...

    private void Timer_Tick(object sender, EventArgs e)
    {
        switch (time%5)
            {
                case 0:
                    if (txt1.Text != string.Empty)
                        SendKeys.Send(this.txt1.Text);
                    break;
    
                case 1:
                    if (txt2.Text != string.Empty) 
                        SendKeys.Send(this.txt2.Text);
                    break;
    
                //finish the switch
            }
    
            SendKeys.Send("{ENTER}");
            time++;
        }
    }
    

    you could even use

    this.Controls.Find("txt"+(time%5 + 1))