有没有办法在winforms中为标签页的标签添加颜色?

我正在努力找到为WinForms中的标签页的标题标题着色的方法。 有一些解决方案可以使用OnDrawItem事件为当前索引选项卡着色,但是可以一次为不同颜色的所有选项卡着色,以使用户对某种行为直观。

提前致谢,

Rajeev Ranjan Lall

是的,不需要任何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属性设置为“Fixed”,然后更改ItemSize属性。

Ash的答案的改进版本:

 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的原始代码。

使用当前的选项卡控件, 如果可能的话,您需要挂钩很多win-32事件(可能有预先包装的实现)。 另一种选择是第三方选项卡式控制替换; 我相信很多供应商会卖给你一个。

IMO,你可能会发现看WPF不那么痛苦; 这是一个很大的变化,但对这样的事情有更多的控制权。 如果需要,你可以在winforms中托管WPF(如果你不能certificate完全修改,这是一个非常普遍的现实)。