效果:

Winfrom各种老毛病真的不适合做大型项目,甚至中型项目都不适合,一些小功能都能把你折腾半死,比如,我想在界面上显示一个进度条,用来显示现在硬盘和内存已经使用了多少,使用了 ProgressBar 控件你看看效果:

进度条中间一直有个白色光影在晃来晃去的,是不是想让别人感慨:“哇!好强的光芒,我的眼睛快睁不开了...”。而且背景颜色无法改变,这个动画也无法关掉,为了解决这两个问题,我找了很久,终于找到了下面的解决方法。
于是我在网上找了一些资料,有到效果有,但不是特别漂亮,比如下面这个
另外,我参考了下面到帖子
Winform自定义控件-进度条/图片图标进度条_思无心的博客-CSDN博客_winform进度条控件
添加一个用户控件,取名为 ProgressBarControl

添加完成后,界面如下

我们将界面调整一下,让其看上去像个进度条,比如宽度 250,高度 30

代码:
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
-
- namespace 自定义控件
- {
- public partial class ProgressBarControl : UserControl
- {
- private int val;//进度值
- private Color PBackgroundColor = Color.FromArgb(217, 218, 219);//初始化颜色
- private Color PForegroundColor = Color.Green;
-
- public ProgressBarControl()
- {
- InitializeComponent();
- }
-
- /// <summary>
- /// 背景色
- /// </summary>
- public Color pBackgroundColor
- {
- get => PBackgroundColor;
- set
- {
- PBackgroundColor = value;
- this.BackColor = PBackgroundColor;
- }
- }
-
- /// <summary>
- /// 前景色
- /// </summary>
- public Color pForegroundColor
- {
- get => PForegroundColor;
- set => PForegroundColor = value;
- }
-
- /// <summary>
- /// 当前值
- /// </summary>
- public int Val
- {
- get => val;
- set
- {
- val = value;
- this.Invalidate();
- }
- }
-
-
- protected override void OnPaint(PaintEventArgs e)
- {
- Graphics g = e.Graphics;
- SolidBrush brush = new SolidBrush(PForegroundColor);
- float percent = val / 100f;
- Rectangle rect = this.ClientRectangle;
- rect.Width = (int)((float)rect.Width * percent);
- rect.Height = this.Height;
- g.FillRectangle(brush, rect);
- brush.Dispose();
- g.Dispose();
- }
-
- private void InitializeComponent()
- {
- this.SuspendLayout();
- this.Name = "ProgressBarControl";
- this.Size = new System.Drawing.Size(250, 30);
- this.ResumeLayout(false);
-
- }
- }
- }
添加代码完成后,就完成了基本的操作了,下面开始使用
先点击Form1 界面,在工具箱就可以看到 命名空间对应的自定义组件了

将 ProgressBarControl 控件直接拖入到Form1中即可,如下

然后在属性窗体就可以看到比Winform的ProgressBar多出来一些功能,这就是你在代码中添加的

我们可以将背景颜色改为其他颜色

改变进度条到进度,使用下面代码即可
progressBarControl1.Val = 50;
效果:

本案例源码:点击下载
如果这个帖子对你有用,欢迎 关注 + 点赞 + 留言,谢谢
end