Hi @Shaifali jain , Welcome to Microsoft Q&A,
I don't recommend using goto: statements, it makes the code difficult to maintain and understand.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private int counter = 0;
private int mimic = 0;
private string text;
private int state = 0;
private const int MaxCounterValue = 20; // Can be adjusted as needed
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
text = label1.Text;
mimic = text.Length;
label1.Text = " Please Wait...";
state = 0;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter++;
switch (state)
{
case 0:
if (counter > mimic)
{
state = 1;
counter = 0;
label1.ForeColor = Color.Lime;
}
else
{
label1.Text = text.Substring(0, counter);
label1.ForeColor = (label1.ForeColor == Color.Lime) ? Color.Red : Color.Lime;
}
break;
case 1:
if (counter > MaxCounterValue)
{
state = 2;
counter = 0;
label1.ForeColor = Color.Red;
}
break;
case 2:
if (counter > MaxCounterValue)
{
state = 0;
counter = 0;
}
break;
}
}
}
}
In addition to using timer controls, you can also use await to achieve similar animation effects. You can use async and await to manage asynchronous operations.
Because using the timer control will trigger events on the Ui thread regularly, it may block the main thread. Asynchronous operations using await will not block the UI thread.
And you don't need to calculate the time manually.
Code show as below:
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _9_19_x
{
public partial class Form1 : Form
{
private string text;
private int state = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
text = label1.Text;
label1.Text = "Please Wait...";
Task task = AnimateTextAsync();
//MessageBox.Show("Task started."); Execute immediately
//await AnimateTextAsync(); needs to change Form1_Load to async
//MessageBox.Show("Task started."); will not be executed immediately
}
private async Task AnimateTextAsync()
{
while (true)
{
switch (state)
{
case 0:
for (int i = 1; i <= text.Length; i++)
{
label1.Text = text.Substring(0, i);
label1.ForeColor = Color.Lime;
await Task.Delay(100); // wait 1 second
}
state = 1;
break;
case 1:
await Task.Delay(1000); // wait 1 second
label1.ForeColor = Color.Red;
await Task.Delay(1000); // wait 1 second
state = 2;
break;
case 2:
await Task.Delay(1000); // wait 1 second
state = 0;
label1.Text = "Please Wait...";
break;
}
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.