VB.NET Progress bar percentage

2019-07-22 12:49发布

问题:

I created a progress bar which works perfectly. I recently added percentages but I'd like to display the label on top of the progress bar.

Like so:

The only problem as you can see is that the background is not transparent. Dispite having:

lblPercentage.BackColor = Color.Transparent

on form load... Is there something that can be done for this?

回答1:

The Transparent BackColor actually works. The problem is that the label gets its BackColor from the form, since the form is its Parent. Therefore we must make the progress bar its parent and adapt its location as well, since now it must be specified relative to the progress bar. Add this code to your form:

Public Sub New()
    InitializeComponent()

    Dim pos As Point = PointToScreen(lblPercentage.Location)
    pos = myProgressBar.PointToClient(pos)
    lblPercentage.Parent = myProgressBar
    lblPercentage.Location = pos
    lblPercentage.BackColor = Color.Transparent
End Sub

Alternatively you can calculate the location of the label like this

lblPercentage.Location = New Point(lblPercentage.Location.X - myProgressBar.Location.X,
                                   lblPercentage.Location.Y - myProgressBar.Location.Y)

You cannot make this in the designer, since your progress bar is probably not a container control (i.e. placing a label on it does not make it a child control of the bar) and you will not see the result in the designer.


UPDATE

You could also try these alternatives:

  • Draw the percentage number in the OnPaint method of your control (override OnPaint).
  • Do what I showed you above inside the progress bar. You could add the label programmatically in the constructor of the progress bar.
  • Use a UserControl as base class of your progress bar. This would allow you to place the label on it in the designer.


回答2:

here you have made your progress bar transparent that means it transparent only to progress bar and behind the progress bar there is form, thats why it showing form. It's a Windows restriction that transparency effects are relative to the top-level window, stacking effects do not work.always You will see the form as the background,