<code>Microsoft Visual Studio Professional 2022 (64-bit) - Current Version 17.11.3</code>

问题描述 投票:0回答:1
TextBox

的最大值设置,我还有另一个显示了

ProgressBar
的当前值。

当应用程序正在运行时,我有一个将最大值设置为2436的过程,我可以看到这反映在

TextBox

中。  递增
ProgressBar
的函数
ProgressBar
由于某种原因,即使
TextBox
表示
ProgressBar

值到

public void IncrementProgressBar() { Action<ProgressBar> incProgressBar = delegate(ProgressBar pgbCtrl) { if (pgbCtrl.Value < pgbCtrl.Maximum) { pgbCtrl.Value++; } tbIndex.Text = pgbCtrl.Value.ToString(); tbMaximum.Text = pgbCtrl.Maximum.ToString(); }; if (pgbOverall.InvokeRequired) { pgbOverall.Invoke((MethodInvoker)delegate() { incProgressBar(pgbOverall); }); } else { incProgressBar(pgbOverall); } }

TextBox
没有的值时,
ProgressBar
显示了正确的值,尽管它向
Maximum

递增了
ProgressBar

Maximum

从未显示
Maximum
.
我有一个呼叫
Appliication.DoEvents();
,它总是在
IncrementProgressBar
函数之后调用。
发生了什么?
    

我有一些建议,以确保您的进度栏显示达到最大值。首先是简单地以100的默认值离开。(将其视为0-100%。)。

然后,当您计算“百分比”时,请使用

ProgressBar.Maximum
如果有任何伪造的舍入错误,并且出于相同的原因将
Math.Ceiling
限制为

progressBar.Value

Math.Min
c#
1个回答
0
投票
最终,请汉斯(Hans)的建议在隐藏汉斯(Hans)的完整进度栏上持续一两秒钟以进行整体效果。

public partial class MainForm : Form, IProgress<(int index, int max)> { public MainForm() { InitializeComponent(); _progress = new(); _progress.ProgressChanged += (sender, e) => { progressBar.Value = Math.Min( progressBar.Maximum, (int)Math.Ceiling((100 * e.index) / Math.Max(e.max, 1d))); tbIndex.Text = e.index.ToString(); }; buttonRun.Click += async (sender, e) => { try { buttonRun.Enabled = false; progressBar.Visible = true; if (int.TryParse(tbIndex.Text, out var index) && int.TryParse(tbMaximum.Text, out var max)) { if (index == max) index = 0; await Task.Run(async () => { while (index <= max) { Report((index, max)); // Simulate background thread work... Thread.Sleep(TimeSpan.FromMilliseconds(1)); index++; } // Enjoy the max progress 100%. await Task.Delay(TimeSpan.FromSeconds(2)); }); } } finally { progressBar.Visible = false; buttonRun.Enabled = true; } }; } public void Report((int index, int max) value)=> ((IProgress<(int index, int max)>)_progress).Report(value); private readonly Progress<(int index, int max)> _progress; }

如果您使用一个实例

System.Progress<T>

实现您的

MainForm
,则不需要
IProgress<T>
(*如果您将ui sychronization-context的位置实例化,则如上图中所示)。

	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.