Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't seem to get progressbar to animate

Tags:

c#

winforms

OK so I've have a problem looking like this.

public Class A{

     public A(){
         progressBar.Style = ProgressBarStyle.Marquee;
         progressBar.MarqueeAnimationSpeed = 0;    
     }

     public void DoSomething(){
         if(checkpasses){
             progressBar.MarqueeAnimationSpeed = 100;
             //Do something here...
             progressBar.MarqueeAnimationSpeed = 0;
         }
         else
             //Do nothing...
         }
}

The problem is that my progressbar wont start moving at all. First I figured that it wont create a new thread by itself (which I find wired) so I tried creating a thread but still the same result. Nothing happens. Is it something I've forgotten?

like image 819
user1106784 Avatar asked Dec 19 '11 22:12

user1106784


2 Answers

Call

Application.EnableVisualStyles();

at the very beginning of your application.

like image 117
Konstantin Spirin Avatar answered Nov 18 '22 17:11

Konstantin Spirin


Your "do something here" code is going to block the UI thread so you will not see the progress bar update until after the DoSomething method completes. At that time you are setting the animation speed back to 0.

Try putting your "do something here" code on a separate thread. When that thread completes set the animation speed back to 0.

Something like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        progressBar1.MarqueeAnimationSpeed = 0;
        progressBar1.Style = ProgressBarStyle.Blocks;
        progressBar1.Value = progressBar1.Minimum;
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        DoSomething();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        progressBar1.Style = ProgressBarStyle.Marquee;
        progressBar1.MarqueeAnimationSpeed = 100;
        backgroundWorker1.RunWorkerAsync();
    }

    private void DoSomething()
    {
        Thread.Sleep(2000);
    }
}
like image 45
Dave Avatar answered Nov 18 '22 16:11

Dave