Windows 窗体 ProgressBar: 启动/停止选框的最简单方法?

我使用的是 C # 和 Windows 窗体。我有一个正常的进度条工作良好的程序,但现在我有另一个操作,其中的持续时间不容易计算。我想显示一个进度条,但不知道开始/停止滚动选框的最佳方法。我希望一些简单的设置,如设置选框速度,然后有一个开始()和停止() ,但它似乎不是那么简单。我必须在后台运行一个空循环吗?我该怎么做?谢谢

232479 次浏览

you can use a Timer (System.Windows.Forms.Timer).

Hook it's Tick event, advance then progress bar until it reaches the max value. when it does (hit the max) and you didn't finish the job, reset the progress bar value back to minimum.

...just like Windows Explorer :-)

There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).

Use a progress bar with the style set to Marquee. This represents an indeterminate progress bar.

myProgressBar.Style = ProgressBarStyle.Marquee;

You can also use the MarqueeAnimationSpeed property to set how long it will take the little block of color to animate across your progress bar.

It's not how they work. You "start" a marquee style progress bar by making it visible, you stop it by hiding it. You could change the Style property.

To start/stop the animation, you should do this:

To start:

progressBar1.Style = ProgressBarStyle.Marquee;
progressBar1.MarqueeAnimationSpeed = 30;

To stop:

progressBar1.Style = ProgressBarStyle.Continuous;
progressBar1.MarqueeAnimationSpeed = 0;

This code is a part of a login form where the users wait for the authentication server to respond.

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;


namespace LoginWithProgressBar
{
public partial class TheForm : Form
{
// BackgroundWorker object deals with the long running task
private readonly BackgroundWorker _bw = new BackgroundWorker();


public TheForm()
{
InitializeComponent();


// set MarqueeAnimationSpeed
progressBar.MarqueeAnimationSpeed = 30;


// set Visible false before you start long running task
progressBar.Visible = false;


_bw.DoWork += Login;
_bw.RunWorkerCompleted += BwRunWorkerCompleted;
}


private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// hide the progress bar when the long running process finishes
progressBar.Hide();
}


private static void Login(object sender, DoWorkEventArgs doWorkEventArgs)
{
// emulate long (3 seconds) running task
Thread.Sleep(3000);
}


private void ButtonLoginClick(object sender, EventArgs e)
{
// show the progress bar when the associated event fires (here, a button click)
progressBar.Show();


// start the long running task async
_bw.RunWorkerAsync();
}
}
}

Many good answers here already, although you also need to keep in mind that if you are doing long-running processing on the UI thread (generally a bad idea), then you won't see the marquee moving either.