启用Application.EnableVisualStyles()后WinForms进度条颜色无法修改的解决办法
解决Application.EnableVisualStyles()下进度条颜色无法修改的问题
启用Application.EnableVisualStyles()后,进度条会默认使用系统主题样式,导致直接设置ForeColor和BackColor失效。以下是无需删除该语句的可行解决方法:
方法一:自定义绘制进度条(OwnerDraw)
通过开启进度条的自绘模式,完全控制绘制逻辑,不受系统主题限制。
- 在设计器中选中目标进度条,将
OwnerDraw属性设为true。 - 绑定进度条的
DrawItem事件,编写自定义绘制代码:
private void progressBar1_DrawItem(object sender, DrawItemEventArgs e) { var pb = sender as ProgressBar; if (pb == null) return; // 绘制进度条背景 using var bgBrush = new SolidBrush(Color.LightGray); e.Graphics.FillRectangle(bgBrush, e.Bounds); // 计算进度填充宽度 var fillWidth = (int)((double)pb.Value / pb.Maximum * pb.Width); // 绘制进度填充部分 using var fillBrush = new SolidBrush(Color.Green); e.Graphics.FillRectangle(fillBrush, 0, 0, fillWidth, pb.Height); // 绘制边框(可选) using var borderPen = new Pen(Color.DarkGray); e.Graphics.DrawRectangle(borderPen, new Rectangle(0, 0, pb.Width - 1, pb.Height - 1)); }
这种方式可以完全自定义进度条的颜色、形状,灵活性最高。
方法二:通过Windows API禁用进度条的主题样式
调用系统API修改进度条的窗口扩展样式,使其忽略系统主题,恢复颜色设置的有效性。
首先定义API调用的辅助类:
using System.Runtime.InteropServices; public static class ProgressBarHelper { private const int GWL_EXSTYLE = -20; private const int WS_EX_COMPOSITED = 0x02000000; [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex); [DllImport("user32.dll", SetLastError = true)] private static extern IntPtr SetWindowLongPtr(IntPtr hWnd, int nIndex, IntPtr dwNewLong); public static void DisableThemedDrawing(ProgressBar pb) { var exStyle = GetWindowLongPtr(pb.Handle, GWL_EXSTYLE); exStyle |= (IntPtr)WS_EX_COMPOSITED; SetWindowLongPtr(pb.Handle, GWL_EXSTYLE, exStyle); pb.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); } }
然后在窗体的Load事件中调用:
private void Form1_Load(object sender, EventArgs e) { ProgressBarHelper.DisableThemedDrawing(progressBar1); // 现在可以正常设置颜色 progressBar1.ForeColor = Color.Blue; progressBar1.BackColor = Color.LightCyan; }
该方法仅针对单个进度条生效,不会影响其他控件的视觉样式。
内容的提问来源于stack exchange,提问作者spery20
相关产品推荐
相关产品推荐

