Question

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..

Was it helpful?

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))

OTHER TIPS

Use 5 different timers, 1 for each or the answer above.

Start out throwing all of the textboxes into a collection:

private List<Textbox> textboxes = new List<Textbox>(){txt1, txt2, txt3};

Have a variable to keep track of the next textbox to show:

private int nextTextBox = 0;

And now to pull it all together:

private void Timer_Tick(object sender, EventArgs e)
{
    var textbox = textboxes[nextTextBox];
    nextTextBox = (nextTextBox + 1) % textboxes.Count; //you can put this inside the if if that's what you want
    if (!string.IsNullOrEmpty(textbox.Text))
    {
        SendKeys.Send(textbox.Text);
        SendKeys.Send("{ENTER}");
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top