2011-03-17 939 views
18

問候,設置TabPage的標題顏色

我有一個標籤控制,我想有標籤的1有它的文本顏色變化:事件。 我找到答案像C# - TabPage Color eventC# Winform: How to set the Base Color of a TabControl (not the tabpage) 但使用這些設置所有顏色,而不是一個。

所以我希望有一種方法來實現這個選項卡我希望改變爲一種方法而不是一個事件?

喜歡的東西:

public void SetTabPageHeaderColor(TabPage page, Color color) 
{ 
    //Text Here 
} 

回答

24

如果你想要的顏色的標籤,請嘗試以下代碼:

this.tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed; 
this.tabControl1.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.tabControl1_DrawItem); 

private Dictionary<TabPage, Color> TabColors = new Dictionary<TabPage, Color>(); 
private void SetTabHeader(TabPage page, Color color) 
{ 
    TabColors[page] = color; 
    tabControl1.Invalidate(); 
} 
private void tabControl1_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    //e.DrawBackground(); 
    using (Brush br = new SolidBrush (TabColors[tabControl1.TabPages[e.Index]])) 
    { 
     e.Graphics.FillRectangle(br, e.Bounds); 
     SizeF sz = e.Graphics.MeasureString(tabControl1.TabPages[e.Index].Text, e.Font); 
     e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, e.Font, Brushes.Black, e.Bounds.Left + (e.Bounds.Width - sz.Width)/2, e.Bounds.Top + (e.Bounds.Height - sz.Height)/2 + 1); 

     Rectangle rect = e.Bounds; 
     rect.Offset(0, 1); 
     rect.Inflate(0, -1); 
     e.Graphics.DrawRectangle(Pens.DarkGray, rect); 
     e.DrawFocusRectangle(); 
    } 
} 
+0

仍然基於一個事件。我想要一個像「SetTabHeader(TabPage頁面,顏色顏色)」 – 2011-03-17 11:54:27

+0

@Levisaxos的方法,我已經添加了您需要的方法。但你仍然需要這個事件。 – 2011-03-17 12:00:40

+0

工程就像一個魅力!非常感謝你! – 2011-03-17 13:39:38

16

對於的WinForms用戶閱讀這一點 - 這僅適用於如果您將標籤控件的DrawMode到OwnerDrawFixed - 如果DrawItem事件設置爲「正常」,則不會觸發DrawItem事件。

+0

謝謝你!這就是爲什麼它不是射擊! :) – 2014-05-14 14:09:46

6

爲了增加樂門Pieng的答案,精美的作品上水平製表,如果你使用豎直突出(像我),那麼你就需要這樣的事:

private void tabControl2_DrawItem(object sender, DrawItemEventArgs e) 
    { 
     using (Brush br = new SolidBrush(tabColorDictionary[tabControl2.TabPages[e.Index]])) 
     { 
      // Color the Tab Header 
      e.Graphics.FillRectangle(br, e.Bounds); 
      // swap our height and width dimensions 
      var rotatedRectangle = new Rectangle(0, 0, e.Bounds.Height, e.Bounds.Width); 

      // Rotate 
      e.Graphics.ResetTransform(); 
      e.Graphics.RotateTransform(-90); 

      // Translate to move the rectangle to the correct position. 
      e.Graphics.TranslateTransform(e.Bounds.Left, e.Bounds.Bottom, System.Drawing.Drawing2D.MatrixOrder.Append); 

      // Format String 
      var drawFormat = new System.Drawing.StringFormat(); 
      drawFormat.Alignment = StringAlignment.Center; 
      drawFormat.LineAlignment = StringAlignment.Center; 

      // Draw Header Text 
      e.Graphics.DrawString(tabControl2.TabPages[e.Index].Text, e.Font, Brushes.Black, rotatedRectangle, drawFormat); 
     } 
    } 

我會回顯ROJO1969提出的觀點,如果這是在WinForms的 - 那麼你必須設置DrawMode到OwnerDrawFixed

特別感謝這個精彩的blog entry,它描述瞭如何在表單上旋轉文本。