Color of ProgressBar is not changing c#

橙三吉。 提交于 2019-12-21 17:50:48

问题


My requirement is to change the color of progress bar to red whenever I click a button. I don't want to comment out Application.EnableVisualStyles().

So I tried using SendMessage. My code:

    [DllImport("user32.dll")]
    private static extern bool SendMessage(IntPtr hWnd, Int32 msg, Int32 wParam, Int32 lParam);

    private const Int32 WM_USER = 0x0400;
    private const Int32 CCM_FIRST = 0x2000;
    private const Int32 PBM_SETBARCOLOR = WM_USER + 9;
    private const Int32 PBM_SETBKCOLOR = CCM_FIRST + 1;

    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Invoke((MethodInvoker)delegate
        {
            SendMessage(this.progressBar1.Handle, PBM_SETBARCOLOR, 0, ColorTranslator.ToWin32(Color.Red));
            SendMessage(this.progressBar1.Handle, PBM_SETBKCOLOR, 0, ColorTranslator.ToWin32(Color.Red));
            progressBar1.Style = ProgressBarStyle.Continuous;
            progressBar1.Value = progressBar1.Maximum;
        });
    }

It is not working. I don't know why. Can u please help


回答1:


If you want to change ProgressBar color from initial Green to Red (which is a standard state) you can do simply

https://msdn.microsoft.com/ru-ru/library/windows/desktop/bb760850(v=vs.85).aspx

  // 1040 - PBM_SETSTATE
  // 2 - red (error), 3 - yellow (paused), 1 - green (in progress) 
  SendMessage(progressBar1.Handle, 1040, 2, 0);

The implementation:

  this.Invoke(() => {
    progressBar1.Value = progressBar1.Maximum;
    progressBar1.Style = ProgressBarStyle.Continuous;

    SendMessage(progressBar1.Handle, 1040, 2, 0); 
  });


来源:https://stackoverflow.com/questions/34268233/color-of-progressbar-is-not-changing-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!