I am writing a program which will type a line of text in 5 second interval. Now, what I am trying to do is to add function which will type the text character by character with small spaces between each character. I am trying to use Thread.Sleep but I my program crashes, and I’m not sure why.
How to do this properly?
private void Interval(object sender, EventArgs e)
{
if (cbPause.Checked == false)
{
SendKeys.Send(txtText.Text + "{enter}");
if (tbType.SelectedTab == tbInterval) tmrInterval.Interval = int.Parse(nudInterval.Value.ToString());
if (tbType.SelectedTab == tbRange) tmrInterval.Interval = random.Next(int.Parse(nudMin.Value.ToString()), int.Parse(nudMax.Value.ToString()));
}
else if (cbPause.Checked == true)
{
Random random = new Random();
foreach (char character in charList)
{
SendKeys.Send(character.ToString());
Thread.Sleep(1000);
}
SendKeys.Send("{enter}");
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (txtText.TextLength < 1 || txtText.Text == string.Empty)
{
lblMessage.Text = "You must type text to proceed!";
btnStart.Enabled = false;
}
else
{
foreach (char character in txtText.Text)
{
charList.Add(character);
}
if (tbType.SelectedTab == tbInterval)
{
tmrDelay.Enabled = true;
txtText.Enabled = false;
nudInterval.Enabled = false;
nudMin.Enabled = false;
nudMax.Enabled = false;
btnStart.Enabled = false;
btnStop.Enabled = true;
}
if (tbType.SelectedTab == tbRange)
{
tmrDelay.Enabled = true;
tbType.Enabled = false;
txtText.Enabled = false;
nudInterval.Enabled = false;
nudMin.Enabled = false;
nudMax.Enabled = false;
btnStart.Enabled = false;
btnStop.Enabled = true;
}
lblMessage.Text = "Starting auto typing in: 3";
}
}
If you call
Thread.Sleep, this is going to hang your GUI thread.What I would do, is use a
System.Windows.Forms.Timer, and everyTick, have it type the next character.Note: If it’s not obvious, this code requires a form with a
textBox1and a button who’sClickevent is wired tobutton1_Click().If you want the first character to be sent right away, you can “cheat” by calling the
Tickhandler right away when you start the timer, by adding the following line: