如何在ProgressBar上放置文本?

San*_*hak 41 c# winforms progress-bar

我在我的c#桌面应用程序中使用了ProgressBar Control.我已经在一个线程中使用它,然后是已经声明控制的线程.它工作正常.现在我想知道如何在进度条控件中显示一些文本,如"启动注册"等.我也想用它作为Marquee进度条.请帮助我.

cod*_*ger 62

您将不得不重写OnPaint方法,调用基本实现并绘制您自己的文本.

您需要创建自己的CustomProgressBar,然后覆盖OnPaint以绘制您想要的文本.

自定义进度栏类

namespace ProgressBarSample
{

public enum ProgressBarDisplayText
{
    Percentage,
    CustomText
}

class CustomProgressBar: ProgressBar
{
    //Property to set to decide whether to print a % or Text
    public ProgressBarDisplayText DisplayStyle { get; set; }

    //Property to hold the custom text
    public String CustomText { get; set; }

    public CustomProgressBar()
    {
        // Modify the ControlStyles flags
        //http://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles.aspx
        SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Rectangle rect = ClientRectangle;
        Graphics g = e.Graphics;

        ProgressBarRenderer.DrawHorizontalBar(g, rect);
        rect.Inflate(-3, -3);
        if (Value > 0)
        {
            // As we doing this ourselves we need to draw the chunks on the progress bar
            Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
            ProgressBarRenderer.DrawHorizontalChunks(g, clip);
        }

        // Set the Display text (Either a % amount or our custom text
        string text = DisplayStyle == ProgressBarDisplayText.Percentage ? Value.ToString() + '%' : CustomText;


        using (Font f = new Font(FontFamily.GenericSerif, 10))
        {

            SizeF len = g.MeasureString(text, f);
            // Calculate the location of the text (the middle of progress bar)
            // Point location = new Point(Convert.ToInt32((rect.Width / 2) - (len.Width / 2)), Convert.ToInt32((rect.Height / 2) - (len.Height / 2)));
            Point location = new Point(Convert.ToInt32((Width / 2) - len.Width / 2), Convert.ToInt32((Height / 2) - len.Height / 2)); 
            // The commented-out code will centre the text into the highlighted area only. This will centre the text regardless of the highlighted area.
            // Draw the custom text
            g.DrawString(text, f, Brushes.Red, location);
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

示例WinForms应用程序

using System;
using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;

namespace ProgressBarSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // Set our custom Style (% or text)
            customProgressBar1.DisplayStyle = ProgressBarDisplayText.CustomText;
            customProgressBar1.CustomText = "Initialising";
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            customProgressBar1.Value = 0;
            btnStart.Enabled = true;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            btnReset.Enabled = false;
            btnStart.Enabled = false;

            for (int i = 0; i < 101; i++)
            {

                customProgressBar1.Value = i;
                // Demo purposes only
                System.Threading.Thread.Sleep(100);

                // Set the custom text at different intervals for demo purposes
                if (i > 30 && i < 50)
                {
                    customProgressBar1.CustomText = "Registering Account";
                }

                if (i > 80)
                {
                    customProgressBar1.CustomText = "Processing almost complete!";
                }

                if (i >= 99)
                {
                    customProgressBar1.CustomText = "Complete";
                }
            }

            btnReset.Enabled = true;


        }


    }
}
Run Code Online (Sandbox Code Playgroud)

  • @MatthewLock:我已经为Custom Progress Bar类和Sample Application添加了代码.希望这可以帮助 (2认同)
  • 很棒的代码!这应该是@Muse 的答案。两件事:修正百分比计算---&gt; int percent = (int)(((double)this.Value / (double)this.Maximum) * 100); 字符串文本 = DisplayStyle == ProgressBarDisplayText.Percentage ?percent.ToString() + '%' : CustomText; ------------- 和第二个: ----- 停止闪烁,正如 KraangPrime 建议的那样添加 ---&gt; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); (2认同)

小智 14

避免闪烁文本

Barry提供的解决方案非常出色,但存在"闪烁问题".

一旦值高于零,OnPaint将重复进行,文本将闪烁.

有一个解决方案.我们不需要VisualStyles作为对象,因为我们将使用我们自己的代码绘制它.

将以下代码添加到Barry编写的自定义对象中,您将避免闪烁:

    [DllImportAttribute("uxtheme.dll")]
    private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);

    protected override void OnHandleCreated(EventArgs e)
    {
        SetWindowTheme(this.Handle, "", "");
        base.OnHandleCreated(e);
    }
Run Code Online (Sandbox Code Playgroud)

我自己也没写过.它在这里找到了:https://stackoverflow.com/a/299983/1163954

我试过它并且它有效.

  • 您还可以通过向控件初始化添加`SetStyle(ControlStyles.OptimizedDoubleBuffer,true);`来避免闪烁. (9认同)

And*_*rew 13

我写了没有闪烁的 TextProgressBar

您可以在这里找到源代码:https : //github.com/ukushu/TextProgressBar

在此处输入图片说明

样品:

在此处输入图片说明 在此处输入图片说明 没有闪烁/闪烁的TextProgressBar 没有闪烁/闪烁的TextProgressBar 在此处输入图片说明 在此处输入图片说明


Dam*_*ash 9

我创建了一个名为InfoProgresBar的控件,它为该功能提供了一个或两个标签(主作业,当前作业)和ProgressBar,并使用它来代替那个ProgressBar.


poo*_*dad 5

我已经使用了这个简单的代码,并且可以正常工作!

for (int i = 0; i < N * N; i++)
     {
        Thread.Sleep(50);
        progressBar1.BeginInvoke(new Action(() => 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));
     }
Run Code Online (Sandbox Code Playgroud)

它只有一个简单的问题,就是这样:当进度条开始上升时,百分比有时会隐藏,然后再次出现。我不是自己写的,而是在这里找到的: C#中ProgressBar上的文本

我使用了这段代码,它确实起作用。

  • 这很糟糕,因为它会泄漏Graphics对象,并且在被遮挡后不会重绘。 (2认同)