【发布时间】:2011-09-18 17:00:47
【问题描述】:
似乎在 Windows 7 中,设置进度条的值时会发生一些动画。设置值似乎并没有等待动画完成。有没有办法通知进度条何时完成动画?
我有一个示例程序。请看cmets。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
namespace Testing
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form1();
form.Run();
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Run()
{
Thread thread = new Thread
(
delegate()
{
ProgressBarMax = 10;
ProgressValue = 0;
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
ProgressValue++;
}
}
);
EventHandler show = delegate
{
thread.Start();
};
Shown += show;
ShowDialog();
Shown -= show;
}
public int ProgressBarMax
{
set
{
Invoke
(
(MethodInvoker)
delegate
{
progressBar1.Maximum = value;
}
);
}
}
public int ProgressValue
{
get
{
return progressBar1.Value;
}
set
{
Invoke
(
(MethodInvoker)
delegate
{
label1.Text = value.ToString();
progressBar1.Value = value;
// setting the value is not blocking until the
// animation is completed. it seems to queue
// the animation and as a result a sleep of 1 second
// will cause the animation to sync up with the UI
// thread.
// Thread.Sleep(1000); // this works but is an ugly hack
// i need to know if there is a callback to notify me
// when the progress bar has finished animating.
// then i can wait until that callback is handled
// before continuing.
// if not, do i just create my own progress bar?
}
);
}
}
}
}
我的 google kung foo 今天好像死了。谢谢。
【问题讨论】:
-
我只想让进度条的值与其他 ui 组件同步。有 10 步,到第 10 步时,进度显示为 90% 而不是 100%。
-
为什么要调用 form.Run 而不是 Application.Run(new Form1());在主要方法中?如果你按照你正在做的那样做,事情就不会以同样的方式工作......据我了解,Application.Run 必须由 Windows 窗体应用程序调用,总是 !!
-
to davide:这是一个显示问题的示例应用程序。 run 方法可以很容易地放在程序类中。我并不真正关心 Application.Run;我知道更好。问题是在设置
progressBar1.Value = value;之后,进度条会呈现一段时间。 -
致 gertarnold:我通常不关心收到有关进度条功能的通知,但是,Windows 7 在不同的线程上渲染得很糟糕。我有两个选择:1)实现我自己的进度条——这很荒谬,或者 2)找出一个简单的机制来等待进度条完成渲染更新的值。微软做了一些傻事不是我的错,但我现在必须处理它。
标签: c# winforms progress-bar