0

我正在使用 Graphics 类手动创建一个按钮控件,但是当我尝试为鼠标悬停或鼠标按下事件更改按钮的背景颜色时,背景只是继续在现有背景上绘制。
除非我使用 Graphics.Clear(),在这种情况下,它会创建一个黑色背景,并在其上绘制我想要的背景。

这是我的代码:

internal class CloseButton : Control
{
    private Color _backColor = Color.FromArgb(32, 255, 255, 255);

    public CloseButton(Control _parent)
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        SetStyle(ControlStyles.Opaque, true);
        SetStyle(ControlStyles.ResizeRedraw, true);
        this.BackColor = Color.Transparent;
        this.Width = 28;
        this.Height = 23;
        this.Location = new Point(_parent.Width - this.Width, 0);

        this.MouseEnter += new EventHandler(CloseButton_MouseEnter);
        this.MouseLeave += new EventHandler(CloseButton_MouseLeave);
        this.MouseDown += new MouseEventHandler(CloseButton_MouseDown);
    }
    protected override CreateParams CreateParams
    {
        get
        {
            const int WS_EX_TRANSPARENT = 0x20;
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= WS_EX_TRANSPARENT;
            return cp;
        }
    }
    protected override void OnPaint(PaintEventArgs __e)
    {
        Graphics _graphics = __e.Graphics;
        Draw(_graphics);
    }
    private void Draw(Graphics __graphics = null)
    {
        Graphics _graphics;
        if (__graphics == null)
        {
            _graphics = this.CreateGraphics();
        }
        else
        {
            _graphics = __graphics;
        }

        _graphics.SmoothingMode = SmoothingMode.AntiAlias;

        #region "Draw background"
        GraphicsPath _backgroundPath = new GraphicsPath();

        //right line
        _backgroundPath.AddLine(
            new Point(this.Width, 0),
            new Point(this.Width, this.Height - 9));
        //bottom right curve
        _backgroundPath.AddBezier(
            new Point(this.Width, this.Height - 8),
            new Point(this.Width, this.Height - 4),
            new Point(this.Width - 4, this.Height),
            new Point(this.Width - 8, this.Height));
        // bottom line
        _backgroundPath.AddLine(
            new Point(this.Width - 8, this.Height),
            new Point(0, this.Height));
        // left line
        _backgroundPath.AddLine(
            new Point(0, this.Height),
            new Point(0, 0));

        Brush _backgroundBrush = new SolidBrush(_backColor);
        _graphics.FillPath(_backgroundBrush, _backgroundPath);
        #endregion
    }
    private void CloseButton_MouseEnter(Object __sender, EventArgs __e)
    {
        _backColor = Color.FromArgb(64, 255, 255, 255);
        Draw();
    }
    private void CloseButton_MouseLeave(Object __sender, EventArgs __e)
    {
        _backColor = Color.FromArgb(32, 255, 255, 255);
        Draw();
    }
    private void CloseButton_MouseDown(Object __sender, EventArgs __e)
    {
        _backColor = Color.FromArgb(32, 0, 0, 0);
        Draw();
    }
}

我能做些什么来解决这个问题?

4

0 回答 0