问题
I am new in windows programming. In C# I was working with using Visual Studio 2017. Now, Im stuck with a problem. The Problem is that, I am trying to display some text (the progress value) in ProgressBar
in the StatusStrip
but can't find a proper working way to do that. :-(
Can anyone please provide me some ideas or solution to this problem? I shall be glad and thankful to you ! Your answers will be appreciated greatly. :-)
回答1:
ToolStripProgressBar
component uses a ProgressBar
to show the progress and the control doesn't show text. To be able to render a text for control, you need to paint the value yourself. To do so, you can create a custom item deriving from ToolStripProgressBar
. Then you can use NativeWindow
to assign a custom code to WM_PAINT
message of the control:
using System;
using System.Windows.Forms;
using System.Windows.Forms.Design;
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.All)]
public class MyToolStripProgressBar : ToolStripProgressBar
{
public MyToolStripProgressBar() : base()
{
this.Control.HandleCreated += Control_HandleCreated;
}
private void Control_HandleCreated(object sender, EventArgs e)
{
var s = new ProgressBarHelper((ProgressBar)this.Control);
}
}
public class ProgressBarHelper : NativeWindow
{
ProgressBar c;
public ProgressBarHelper(ProgressBar progressBar)
{
c = progressBar;
this.AssignHandle(c.Handle);
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0xF /*WM_PAINT*/)
{
using (var g = c.CreateGraphics())
TextRenderer.DrawText(g, c.Value.ToString(),
c.Font, c.ClientRectangle, c.ForeColor);
}
}
}
回答2:
progressBar1.CreateGraphics().DrawString(progressBar1.Value.ToString(), new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
I had the same question just a jew days ago an ran into this little piece of code that does the job perfectly :)
Got the code and explanation from this Website
来源:https://stackoverflow.com/questions/43138097/show-text-on-progressbar-in-statusstrip