【问题标题】:Color of ProgressBar is not changing c#ProgressBar的颜色没有改变c#
【发布时间】:2015-12-14 13:26:32
【问题描述】:

我的要求是每次单击按钮时将进度条的颜色更改为红色。我不想注释掉 Application.EnableVisualStyles()。

所以我尝试使用 SendMessage。我的代码:

    [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;
        });
    }

它不工作。我不知道为什么。你能帮忙吗

【问题讨论】:

    标签: c# winforms progress-bar


    【解决方案1】:

    如果您想将 ProgressBar 颜色从初始 Green 更改为 Red(这是一种标准状态),您可以这样做

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

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

    实现:

      this.Invoke(() => {
        progressBar1.Value = progressBar1.Maximum;
        progressBar1.Style = ProgressBarStyle.Continuous;
    
        SendMessage(progressBar1.Handle, 1040, 2, 0); 
      });
    

    【讨论】:

    • 这里只是一个小修正。 1 似乎是绿色的值,而不是 0。
    • @DangerZone:你说的很对,不错:PBST_NORMAL = 0x0001; /* green */;但是,如果值超出[1..3] 范围,将使用绿色。我已经编辑了答案
    • 你确定是这样吗?我启动了一个小型测试应用程序来在不同颜色之间切换(以测试它在更大的程序中如何工作),如果在 [1..3] 之外,它似乎会保持当前颜色。
    • @DangerZone:你说的很对;看来我急需更多咖啡;我希望这只是学术兴趣,因为坚持记录在案的[1..3] 范围是最好的政策。
    猜你喜欢
    • 1970-01-01
    • 2011-07-31
    • 2021-08-04
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2014-10-10
    相关资源
    最近更新 更多