How to: Render a Visual Style Element
Collapse the table of content
Expand the table of content

How to: Render a Visual Style Element


The System.Windows.Forms.VisualStyles namespace exposes VisualStyleElement objects that represent the Windows user interface (UI) elements supported by visual styles. This topic demonstrates how to use the VisualStyleRenderer class to render the VisualStyleElement that represents the Log Off and Shut Down buttons of the Start menu.

To render a visual style element

  1. Create a VisualStyleRenderer and set it to the element you want to draw. Note the use of the Application.RenderWithVisualStyles property and the VisualStyleRenderer.IsElementDefined method; the VisualStyleRenderer constructor will throw an exception if visual styles are disabled or an element is undefined.

    Private renderer As VisualStyleRenderer = Nothing
    Private element As VisualStyleElement = _
    Public Sub New()
        Me.Location = New Point(50, 50)
        Me.Size = New Size(200, 200)
        Me.BackColor = SystemColors.ActiveBorder
        If Application.RenderWithVisualStyles And _
            VisualStyleRenderer.IsElementDefined(element) Then
                renderer = New VisualStyleRenderer(element)
        End If
    End Sub
  2. Call the DrawBackground method to render the element that the VisualStyleRenderer currently represents.

    Protected Overrides Sub OnPaint(ByVal e As PaintEventArgs)
        ' Draw the element if the renderer has been set.
        If (renderer IsNot Nothing) Then
            renderer.DrawBackground(e.Graphics, Me.ClientRectangle)
        ' Visual styles are disabled or the element is undefined, 
        ' so just draw a message.
            Me.Text = "Visual styles are disabled."
            TextRenderer.DrawText(e.Graphics, Me.Text, Me.Font, _
                New Point(0, 0), Me.ForeColor)
        End If
    End Sub

Compiling the Code

This example requires:

© 2015 Microsoft