将进度条绘制到按钮背景中

我想基于0到100的输入值显示一个Button内的条形图,例如。值50会将条形图填充到按钮高度的一半。

为此,我在运行时创建了一个按钮。

            Button btn = new Button();
            _panel.Controls.Add(btn);

            btn.Size = new Size(btnW, btnH);
            btn.Location = loc;
            btn.FlatStyle = FlatStyle.Flat;
            btn.FlatAppearance.BorderSize = 2;
            btn.Font = new Font("Microsoft Sans Serif", 12);
            btn.Text = "1";
            btn.TextAlign = ContentAlignment.MiddleCenter;
            btn.Paint += btn_Paint;

然后在绘画活动中


        void btn_Paint(object sender, PaintEventArgs e) {
            Button btn = sender as Button;
            Graphics g = e.Graphics;

            using (SolidBrush brush = new SolidBrush(Color.PeachPuff)) {

                g.FillRectangle(brush, new Rectangle(0, btn.Height / 2, btn.Width, btn.Height/2));
            }
        }

但是我得到这个结果

enter image description here

As can be since the filled rectangle overwrites the border and text, I see that there is no PaintBackground event on the Button.

有没有办法在运行时填充按钮的自定义背景?

评论