无法在Windows窗体上绘制正确的渐变按钮

问题描述 投票:0回答:1

我有以下简单的代码,应该绘制一个渐变按钮,添加为 gradbtn.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace CustomControls.GradientControls
{
    public class Gradbtns : Button
     {
        protected override void OnPaint(PaintEventArgs pevent)
        { 
           
            base.OnPaint(pevent);

            pevent.Graphics.FillRectangle(new LinearGradientBrush(
              new PointF(0, this.Height / 2), new PointF(this.Width, this.Height / 2),
              Color.AliceBlue, Color.BurlyWood), this.ClientRectangle);
        }
    }
}

上述代码绘图的问题在于,它没有启用表单上的“按钮”单击操作,而是看起来就像在表单上绘制的一样。 但是使用“OnPaintBackground”事件确实启用了按钮,但看不到颜色,请参见下图

enter image description here

c# winforms button
1个回答
0
投票

您需要使用OnClick方法来实现点击按钮的功能,下面是一个经过验证的代码示例,对渐变背景的实现和控件外观的设置做了一些优化,应该可以满足您的需求:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace CustomControlsLibrary
{
    public class GradientButton : Button
    {
        public Color GradientColor1 { get; set; } = Color.AliceBlue;
        public Color GradientColor2 { get; set; } = Color.BurlyWood;
        public Color TextColor { get; set; } = Color.DarkBlue;

        protected override void OnPaint(PaintEventArgs pevent)
        {
            base.OnPaint(pevent);

            // Get the graphical object of the control
            Graphics graphics = pevent.Graphics;
            // Create brush for the background gradient
            using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle, GradientColor1, GradientColor2, LinearGradientMode.Horizontal))
            {
                graphics.FillRectangle(brush, this.ClientRectangle);
            }

            // Draw text
            using (SolidBrush textBrush = new SolidBrush(TextColor))
            {
                SizeF textSize = graphics.MeasureString(this.Text, this.Font);
                PointF locationToDraw = new PointF();
                locationToDraw.X = (this.Width / 2) - (textSize.Width / 2);
                locationToDraw.Y = (this.Height / 2) - (textSize.Height / 2);
                graphics.DrawString(this.Text, this.Font, textBrush, locationToDraw);
            }

            // Process control border
            ControlPaint.DrawBorder(graphics, this.ClientRectangle, Color.Black, ButtonBorderStyle.Solid);
        }
        protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);
            MessageBox.Show("Gradient Button Clicked!");
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.