2010-01-21 72 views
25

我很努力地找到方法在WinForms中为Tabpage的标签页标题着色。有一些解决方案使用OnDrawItem事件为当前索引标签着色,但是可以一次为所有标签着色为不同的颜色,以便使用户可以直观地了解某种行为。有没有办法给winforms中的tabpage制表色标签?

由于提前,

拉杰夫·兰詹拉尔

回答

24

是的,不需要任何win32代码。您只需将选项卡控件的DrawMode属性设置为“OwnerDrawFixed”,然后处理选项卡控件的DrawItem事件。

下面的代码说明了如何:

private void tabControl1_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    // This event is called once for each tab button in your tab control 

    // First paint the background with a color based on the current tab 

    // e.Index is the index of the tab in the TabPages collection. 
    switch (e.Index) 
    { 
     case 0: 
      e.Graphics.FillRectangle(new SolidBrush(Color.Red), e.Bounds); 
      break; 
     case 1: 
      e.Graphics.FillRectangle(new SolidBrush(Color.Blue), e.Bounds); 
      break; 
     default: 
      break; 
    } 

    // Then draw the current tab button text 
    Rectangle paddedBounds=e.Bounds; 
    paddedBounds.Inflate(-2,-2); 
    e.Graphics.DrawString(tabControl1.TabPages[e.Index].Text, this.Font, SystemBrushes.HighlightText, paddedBounds); 

} 

设置DrawMode为“OwnerDrawnFixed”是指每个选项卡按钮必须是相同的尺寸(即,固定)。

但是,如果要更改所有选项卡按钮的大小,可以将选项卡控件的SizeMode属性设置为“固定”,然后更改ItemSize属性。

+2

很好用,但是如何改变标签后面区域的颜色? – Roast 2012-05-04 16:04:19

1

使用当前选项卡控制,如果有可能你需要挂接大量的双赢,32事件(有可能是一个预在那里包装的实现)。另一种选择是第三方标签式控制替换;我相信很多厂商会向你推销一个。

国际海事组织,你可能会发现看WPF更少痛苦;这是一个很大的变化,但对这样的事情有更多的控制权。如果需要的话,你可以在WinForms里面托管WPF(如果你不能证明一个完整的转换,这是一个非常普遍的现实)。

38

灰的答案的改进版本:

private void tabControl_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    TabPage page = tabControl.TabPages[e.Index]; 
    e.Graphics.FillRectangle(new SolidBrush(page.BackColor), e.Bounds); 

    Rectangle paddedBounds = e.Bounds; 
    int yOffset = (e.State == DrawItemState.Selected) ? -2 : 1; 
    paddedBounds.Offset(1, yOffset); 
    TextRenderer.DrawText(e.Graphics, page.Text, Font, paddedBounds, page.ForeColor); 
} 

该代码使用TextRenderer类绘制它的文本(如.NET一样),修复了字形裁剪/包装的界限没有负面膨胀,和问题将选项卡选项考虑在内。

感谢Ash为原始代码。

+1

只有当您将选项卡控件的DrawMode设置为OwnerDrawFixed时,此功能才起作用 - 如果DrawItem事件设置为“正常”,则不会触发DrawItem事件。 – Nitesh 2017-02-06 19:57:16

相关问题