Text in progressbar in c #

I am using the following code.

Why is it not working properly?

private void Form1_Shown(object sender, EventArgs e) { for (int i = 1; i <= 100; i++) { Application.DoEvents(); Thread.Sleep(200); progressBar1.Refresh(); progressBar1.Value = i; progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7)); } } 

update:

Why is the text not always displayed?

-2
c # progress-bar
Nov 24 '11 at 15:08
source share
2 answers

This works - although I set the thread-sleep to over 200 ms. Your problem was that you were doing work in the user interface thread and thus never updated. For better visibility, just change the font color:

  private void Form1_Load(object sender, EventArgs e) { Task t = new Task(() => StartUpdate()); t.Start(); t.ContinueWith(task => Console.WriteLine("Done loading")); } private void StartUpdate() { for (int i = 1; i <= 100; i++) { UpdateProgressBar(i); } } private void UpdateProgressBar(int i) { if (progressBar1.InvokeRequired) { progressBar1.Invoke(new Action<int>(UpdateProgressBar), new Object[] { i }); } else { Thread.Sleep(200); progressBar1.Refresh(); progressBar1.Value = i; progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial", (float)10.25, FontStyle.Bold), Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7)); } } 
+1
Nov 24 2018-11-11T17
source share

Use this. There are good ways to do this, but since your question was why, it did not work, due to Application.DoEvents ();

  private void Main_Shown(object sender, EventArgs e) { for (int i = 1; i <= 100; i++) { progressBar1.Value = i; int percent = (int)(((double)(progressBar1.Value -progressBar1.Minimum) / (double)(progressBar1.Maximum - progressBar1.Minimum)) * 100); using (Graphics gr = progressBar1.CreateGraphics()) { gr.DrawString(percent.ToString() + "%", SystemFonts.DefaultFont, Brushes.Black, new PointF(progressBar1.Width / 2 - (gr.MeasureString(percent.ToString() + "%", SystemFonts.DefaultFont).Width / 2.0F), progressBar1.Height / 2 - (gr.MeasureString(percent.ToString() + "%", SystemFonts.DefaultFont).Height / 2.0F))); } System.Threading.Thread.Sleep(200); } } 
-2
Nov 24 '11 at 15:38
source share



All Articles