As time passes and progresses, the label text changes

1

Before you start it's just a game not a virus.

My goal is when when progressbar reaches 1% put the text as downloading virus and when it reaches 50% put the text as installing virus but instead it changes immediately to installing virus .

This is the code so far:

Timer t = new Timer();
private void LetTheGameStart_Load(object sender, EventArgs e)
{
    timer1.Enabled = true;
    timer1.Start();
    timer1.Interval = 1000;
    progressBar1.Maximum = 10;
    timer1.Tick += new EventHandler(timer1_Tick);
}

void timer1_Tick(object sender, EventArgs e)
{
    {
        if (progressBar1.Value != 100)
        {
            progressBar1.Value++;
            label2.Text = "Downloading Virus";
        }
    }
    if (progressBar1.Value != 50)
    {
        label2.Text = "installing Virus";
    }
}
    
asked by anonymous 25.07.2016 / 17:45

1 answer

4

When using ProgressBar it is very useful to use BackgroundWorker to increase the bar (property Value of ProgressBar) and leave the application free to do other things.

Implementing BackgroundWorker

First let's implement event DoWork of BackgroundWorker to report progress:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{            
    for (int i = 1; i <= 100; i++) //loop para o progressbar
    {
        Thread.Sleep(100);
        backgroundWorker1.ReportProgress(i);
    }
}

Then you must implement the ProgressChanged event of BackgroundWorker to get the values being passed to the ProgressBar and handled:

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
    Text = e.ProgressPercentage.ToString();

    if (progressBar1.Value >= 1 && progressBar1.Value <= 50)
    {
        label1.Text = "Installing Virus";                
    }
    else if (progressBar1.Value > 50 && progressBar1.Value <= 100)
    {
        label1.Text = "Downloading Virus";
    }
}

Finally, you just need to invoke the RunWorkerAsync() method of BackgroundWorker to activate it:

private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

PS: The WorkerReportsProgress property of the BackgroundWorker must be set to true to update the progress.

Exit:

When the value is below 50 it displays the message Installing Virus :

Whenthevalueisabove50itdisplaysthemessageDownloadingVirus:

YoucanalsousetheRunWorkerCompletedofBackgroundWorkereventtodosomethingwhenprogressiscomplete.

Source: link

    
25.07.2016 / 18:47