2010-02-19 71 views
0

我正在使用ButtonRenderer在自定義單元格中繪製按鈕。我想按鈕有一個非標準的BackColor。這由普通按鈕支持,但按鈕單元格或ButtonRenderer中沒有任何內容支持它。如何繪製帶有非標準BackColor的按鈕?該方法必須考慮用戶的主題 - 我不能只繪製我自己的按鈕。如何繪製帶有非標準BackColor的按鈕?

回答

2

ButtonRenderer使用VisualStyleRenderer.DrawBackground()繪製按鈕背景。該方法非常瞭解用戶選擇的主題,按鈕的背景將使用主題指定的顏色。使用非標準的BackColor會違反用戶選擇的主題。你不能兩面都有。

Button類實際上並不使用ButtonRenderer,它使用從System.Windows.Forms.ButtonInternal命名空間的內部ButtonBaseAdapter類派生的三個渲染器之一。這些渲染器是內部的,你不能在你自己的代碼中使用它們。用Reflector或Reference Source看看它們的含義。專注於PaintButtonBackground方法。

+0

這是ButtonStandardAdapter.PaintThemedButtonBackground發現竟然是至關重要的一個美化按鈕的外觀 - 它調用ButtonRender.DrawButton,然後收縮了4PX矩形,無論的主題。 – Simon 2010-02-19 13:49:56

-1

使用提供的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); 
    } 
+0

ControlPaint繪製了一個毫無意義的按鈕 - 正如我在問題中所說的,我必須考慮用戶的主題 - 我不能只繪製我自己的按鈕。 – Simon 2010-02-19 15:35:11

+0

對不起,我錯過了。從上面的帖子你似乎發現爲什麼它不允許背景重繪,但你有沒有找到一個解決方案?也有興趣從中學習。 – 2010-02-20 11:17:49

+0

是的 - 正如nobugz所建議的那樣,我使用反射器來看Button是如何做到的。 – Simon 2010-02-22 09:12:32

相關問題