简体   繁体   English

视觉c带有进度条的尖锐进度栏

[英]visual c sharp progress bar with background worker

i have the following code that updates my progress bar in visual c sharp. 我有以下代码可以更新Visual C Sharp中的进度条。 it works fine and the bar moves for each percentage. 它工作正常,并且条形图针对每个百分比移动。 but i also have code that i got from a post on another site, that is suppose to put the progress bar value in the middle of the progress bar as % percentage. 但是我也有我从另一个网站上的帖子中获得的代码,这是假设将进度条的值作为百分比百分比放在进度条的中间。 it displays the % of the progress bar value for a split second but then disappears. 它会瞬间显示进度条值的%,但随后消失。 i am new to c sharp and have tried several things like pBar.update and pBar.refresh after the pBar value change. 我是c的新手,在pBar值更改后尝试了诸如pBar.update和pBar.refresh之类的几项操作。 i have edited some of the code to make it easier to understand. 我已经编辑了一些代码,以使其更易于理解。 see below, once i reportprogress the background worker progresschanged executes and again the pBar value changes i see it change, and also the textbox text gets updated, but for some reason the code further below that draws the % text within the progress bar gets overwritten somehow. 参见下文,一旦我执行了reportprogress,背景工作程序progresschanged就执行了一次,并且再次看到pBar值发生了变化,并且文本框文本也得到了更新,但是由于某种原因,在下方绘制进度条内的%文本的代码被覆盖了。 again i see the % for a split second. 我再次看到%的瞬间。 you can see some of my comments where i was trying various things to see if it would redraw the % 您可以在尝试各种方法的地方查看我的一些评论,以查看它是否会重绘%

         private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        backgroundWorker1.ReportProgress(10);
        collect_long_process();
        }

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

        txtBox_pBar.Text = "Gathering info";

        int percent = 10;//(int)(((double)pBar.Value / (double)pBar.Maximum) * 100);
        pBar.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular),
        Brushes.Black, new PointF(pBar.Width / 2 - 10, pBar.Height / 2 - 7));
    //pBar.Update();
    //Application.DoEvents();
    }

That code is wrong. 那段代码错了。

You need to handle the progress bar's Paint event and draw on e.Graphics . 您需要处理进度条的Paint事件并在e.Graphics上进行e.Graphics
Otherwise, your drawing will be overwritten next time the control paints itself. 否则,下次控件绘制自身时,您的图形将被覆盖。

In general, you should never draw on CreateGraphics() . 通常,永远不要使用CreateGraphics()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM