代码之家  ›  专栏  ›  技术社区  ›  Simon

如何绘制具有非标准背景色的按钮?

  •  0
  • Simon  · 技术社区  · 16 年前

    ButtonRenderer 在自定义单元格中绘制按钮的步骤。我希望这个按钮有一个非标准的背景色。这由普通按钮支持,但按钮单元格或

    2 回复  |  直到 16 年前
        1
  •  2
  •   Hans Passant    16 年前

    ButtonRenderer使用VisualStyleRenderer.DruckGround()绘制按钮背景。该方法非常了解用户选择的主题,按钮的背景将使用主题指定的颜色。使用非标准背景色将违反用户选择的主题。你不能两全其美。

    Button类实际上不使用ButtonRender,它使用从System.Windows.Forms.ButtonInternal命名空间中的内部ButtonBaseAdapter类派生的三个呈现器之一。这些渲染器是内部的,您不能在自己的代码中使用它们。用反射器或参考源查看它们,看看需要什么。重点介绍PaintButtonBackground方法。

        2
  •  -1
  •   Fadrian Sudaman    16 年前

    使用提供的ControlPaint和TextRenderer类绘制您自己的按钮。这相当简单。我很快将这些代码组合起来,向您展示。您可以通过设置边框样式等来美化按钮的外观。

        private ButtonState state = ButtonState.Normal;
        public ButtonCell(): base()
        {
            this.Size = new Size(100, 40);
            this.Location = new Point(50, 50);
            this.Font = SystemFonts.IconTitleFont;
            this.Text = "Click here";     
        }
        private void DrawFocus()
        {
            Graphics g = Graphics.FromHwnd(this.Handle);
            Rectangle r = Rectangle.Inflate(this.ClientRectangle, -4, -4);
            ControlPaint.DrawFocusRectangle(g, r);
            g.Dispose();
        }
        private void DrawFocus(Graphics g)
        {
            Rectangle r = Rectangle.Inflate(this.ClientRectangle, -4, -4);
            ControlPaint.DrawFocusRectangle(g, r);
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (state == ButtonState.Pushed)
                ControlPaint.DrawBorder3D(e.Graphics, e.ClipRectangle, Border3DStyle.Sunken);
            else
                ControlPaint.DrawBorder3D(e.Graphics, e.ClipRectangle, Border3DStyle.Raised);
            TextRenderer.DrawText(e.Graphics, Text, this.Font, e.ClipRectangle, this.ForeColor,
                TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
        }
        protected override void OnGotFocus(EventArgs e)
        {
            DrawFocus();
            base.OnGotFocus(e);
        }
        protected override void OnLostFocus(EventArgs e)
        {
            Invalidate();
            base.OnLostFocus(e);
        }
        protected override void OnMouseEnter(EventArgs e)
        {
            DrawFocus();
            base.OnMouseEnter(e);
        }
    
        protected override void OnMouseLeave(EventArgs e)
        {
            Invalidate();
            base.OnMouseLeave(e);
        }
        protected override void OnMouseDown(MouseEventArgs e)
        {
            state = ButtonState.Pushed;
            Invalidate();
            base.OnMouseDown(e);
        }
        protected override void OnMouseUp(MouseEventArgs e)
        {
            state = ButtonState.Normal;
            Invalidate();
            base.OnMouseUp(e);
        }