Windows Forms TabControl: Using Right-Aligned or Left-Aligned Tabs

I wanted to do something today that I thought was simple: take a Windows Forms TabControl and render the tabs horizontally on the right- or left-hand side of the form. The good news is, it is simple. You just have to know the secret sauce to pull it off.

  1. On TabControl, set the following properties:

    1. .Alignment=Right

    2. .SizeMode=Fixed (Must be set to change ItemSize.Width, below)

    3. .DrawMode=OwnerDrawFixed

  2. Set the ItemSize property to the preferred width and height of your tabs. Since we're owner-drawing, we need the tabs to be a fixed width and height so we have a well-defined area in which to draw the tab labels.

    Here's one of the tricky bits, though: Width and height do not flip even though you are now right-aligned. In other words, you have to change the Width property to change the height (y axis) of the tabs, and change the Height property to change the width (x axis) of the tabs.

  3. Handle DrawItem() and define code to render the text the way you want it. Here's a sampling:

    Private Sub TabControl1_DrawItem(ByVal sender As Object, ByVal e As _
System.Windows.Forms.DrawItemEventArgs) Handles TabControl1.DrawItem
        Dim g As Graphics = e.Graphics
        Dim _TextBrush As Brush

        ' Get the item from the collection.
        Dim _TabPage As TabPage = TabControl1.TabPages(e.Index)

        ' Get the real bounds for the tab rectangle.
        Dim _TabBounds As Rectangle = TabControl1.GetTabRect(e.Index)

        If (e.State = DrawItemState.Selected) Then
            ' Draw a different background color, and don't paint a focus rectangle.
            _TextBrush = New SolidBrush(Color.Red)
            g.FillRectangle(Brushes.Gray, e.Bounds)
            _TextBrush = New System.Drawing.SolidBrush(e.ForeColor)
        End If

        ' Use our own font. Because we CAN.
        Dim _TabFont As New Font("Arial", 10.0, FontStyle.Bold, GraphicsUnit.Pixel)

        ' Draw string. Center the text.
        Dim _StringFlags As New StringFormat()
        _StringFlags.Alignment = StringAlignment.Center
        _StringFlags.LineAlignment = StringAlignment.Center
        g.DrawString(_TabPage.Text, _TabFont, _TextBrush, _TabBounds, New StringFormat(_StringFlags))
    End Sub

Comments (3)

  1. lne818 says:

    使用 Windows Forms 2.0 可以更加轻松地创建高级的动态和导航布局。

  2. 大口仔 says:



Skip to main content