im having some issues with some text im writing on a progress bar, it displays but then will disappear once the GUI thread has finished drawing, and the separate thread running the loop commences again. Im assuming this is because its out of scope but im not sure how to fix it.
the general layout is as follows:
namespace namespace1
{
public partial class Form1:Form
{
....
}
public class ProgressBar
{
public void SubscribeToUpdateEvent()
{
//subscribe incrementPB to event
}
public void IncrementPB(object sender, EventArgs e)
{
//Update progress bar's value
DrawPercentage(value);
}
public void DrawPercentage(Value)
{
using (Graphics Draw = statusBar.CreateGraphics())
{
Draw.DrawString(percentage.ToString() + "%", ProgressBar.DefaultFont, Brushes.Black, new PointF((statusBar.Width / 2) - ((Draw.MeasureString(percentage.ToString() + "%", ProgressBar.DefaultFont)).Width / 2.0F),
(statusBar.Height / 2) - ((Draw.MeasureString(percentage.ToString() + "%", ProgressBar.DefaultFont)).Height / 2.0F)));
}
}
}
//Second file which processes a bunch of data on a separate thread and raises the event after each loop.
namespace namespace2
{
public class MyClass
{
public void iterator()
{
for(int i=0;i<10;i++)
{
//raise event to update the progress bar here
}
}
}
}
Thanks for your help.
The percentage label probably gets erased when the next
Paintevent occurs on the progress bar. Try implementing the progress bar as a user control, this way you can override theOnPaintmethod and render the text there (afterbase.OnPaint(e)).I made a few simple classes to simulate your situation. Here is the approach that works for me:
1) The progress bar control (simple implementation, just to outline the basic idea with OnPaint):
2) Class that represents the job running in a background thread:
3) Form class. Contains the custom progress bar control and starts the background job when a button is pressed.
You can call
Invalidate()internally (inside thePercentageproperty setter), I called it separately just to emphasize how the painting process is triggered.