0

I am now writing the simple Winapps C# to display the progress bar in such way that normally it displays green and turn red when its value > 70 (suppose the value range is 0 to 100).

I read some method at Stack Overflow, I found that there are some complicated method that are just used to change the color of progress bar.

At the properties of Progress bar, there are two parameters Forecolor and backcolor to change the colors of progress bar and I did try to the following codes:

        pgBar1.ForeColor = Color.FromArgb(255, 0, 0);
        pgBar1.BackColor = Color.FromArgb(255, 100, 0);

But it seems doesn't work. I am wonder why not?

Can anyone suggest the simple way to do so?

Thank you.

Chan Cimiy
  • 31
  • 1
  • 3

1 Answers1

1

There is quite an easy way to do this, and I wouldn't call it complicated - simply paste this class anywhere into your project (as suggested by this answer):

public static class ModifyProgressBarColor
{
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr w, IntPtr l);
    public static void SetState(this ProgressBar pBar, int state)
    {
        SendMessage(pBar.Handle, 1040, (IntPtr)state, IntPtr.Zero);
    }
}

As it is an extension method you can use it like this:

pgBar1.SetState(2);

The state is encoded like this:

1 -> green

2 -> red

3 -> yellow

Your solution doesn't work because the BackColor property isn't the color of the bar.

You could, of course, overwrite the paint method of the progress bar to color it in every possible color, but this wouldn't be a simple way, I guess.

Community
  • 1
  • 1
MetaColon
  • 2,895
  • 3
  • 16
  • 38