【问题标题】:How do I change the color of each tab?如何更改每个选项卡的颜色?
【发布时间】:2015-05-04 20:45:34
【问题描述】:

我有一个有四个选项卡的表单我希望每个选项卡都具有不同的颜色。我在互联网上唯一能找到的是如何更改所选选项卡的颜色,而其余选项卡保持原始颜色。我还没有找到任何东西可以让每个标签都有自己的颜色。我目前拥有的代码是。

Private Sub TabControl1_DrawItem(sender As System.Object, e As System.Windows.Forms.DrawItemEventArgs) Handles TabControl1.DrawItem

        Dim g As Graphics = e.Graphics
        Dim tp As TabPage = TabControl1.TabPages(e.Index)
        Dim br As Brush
        Dim sf As New StringFormat

        Dim r As New RectangleF(e.Bounds.X, e.Bounds.Y + 2, e.Bounds.Width, e.Bounds.Height - 2)

        sf.Alignment = StringAlignment.Center

        Dim strTitle As String = tp.Text

        If TabControl1.SelectedIndex = e.Index Then

            'this is the background color of the tabpage header
            br = New SolidBrush(Color.LightSteelBlue) ' chnge to your choice
            g.FillRectangle(br, e.Bounds)

            'this is the foreground color of the text in the tab header
            br = New SolidBrush(Color.Black) ' change to your choice
            g.DrawString(strTitle, TabControl1.Font, br, r, sf)

        Else

            'these are the colors for the unselected tab pages 
            br = New SolidBrush(Color.Blue) ' Change this to your preference
            g.FillRectangle(br, e.Bounds)
            br = New SolidBrush(Color.Black)
            g.DrawString(strTitle, TabControl1.Font, br, r, sf)

        End If
    End Sub

【问题讨论】:

  • 引用:' Change this to your preference。是的,好主意。

标签: vb.net


【解决方案1】:

你需要做两件事:

首先是改变TabControl的DrawMode,设置为OwnerDrawFixed

第二个是处理TabControl DrawItem事件

这是一个例子:

 Private Sub TabControl1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles TabControl1.DrawItem
    Select Case e.Index
        Case 0
            e.Graphics.FillRectangle(New SolidBrush(Color.Red), e.Bounds)
        Case 1
            e.Graphics.FillRectangle(New SolidBrush(Color.Blue), e.Bounds)
        Case 2
            e.Graphics.FillRectangle(New SolidBrush(Color.Magenta), e.Bounds)

    End Select

    Dim paddedBounds As Rectangle = e.Bounds
    paddedBounds.Inflate(-2, -2)
    e.Graphics.DrawString(TabControl1.TabPages(e.Index).Text, Me.Font, SystemBrushes.HighlightText, paddedBounds)


End Sub

这是它的样子(我只更改了前三个标签页的标签颜色,其他可以通过添加新案例来选择案例轻松完成)

【讨论】:

  • 这对我有用。 ownerdrawfixed 使标签标题消失有点奇怪。
【解决方案2】:

TabControl1 是您通过设计器添加到表单的 Tab 控件吗?为什么不在每个选项卡上创建 TabBackColor 属性?

如果不是(您必须通过代码来完成),只需使用循环循环浏览 TabControl1 的选项卡页集合 (TabControl1.TabPages) 中的每个选项卡,并为每个选项卡设置 TabBackColor 属性。

【讨论】:

  • 我相信最初的问题是改变标签本身的颜色,而不是整个标签的背景颜色。此外,您始终可以在设计时访问这些属性,因此如果您在开始时没有这样做,则无需以编程方式更改背景颜色。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 2013-09-25
  • 2015-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多