Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I provide custom styling for Windows Forms, providing a similar function as CSS does for HTML?

Here's what I use it in my code.

1. Set up a form for the user to select their style preferences. If this is not important to your app, go to step 2 and skip step 3.

2. Set up a Preference class.

Imports System.Drawing

Public Class StylePreferences

  Private Shared m_FrmBackColor As Color = Color.Tan
  Private Shared m_FrmTextColor As Color = Color.Black
  Private Shared m_FontFace As Font = New Font("Verdana", 10)
  Private Shared m_ButtonBackColor As Color = Color.Azure

  ' Additional fields...

  Property FrmBackColor() As Color
    Get
      Return m_FrmBackColor
    End Get
    Set(ByVal Value As Color)
      m_FrmBackColor = Value
    End Set
  End Property

  Property FrmTextColor() As Color
    ' ...
  End Property

  Property FontFace() As Font
    ' ...
  End Property

  Property ButtonBackColor() As Color
    ' ...
  End Property

  ' Additional properties...

End Class

3. Create a Preference form for the user to control preferences, assign values from the form to an instance of the preference class:

Private Sub SetStyle()
  Dim style As StylePreferences = New StylePreferences
  style.FrmBackColor = Me.BackColor
  style.FrmTextColor = Me.ForeColor
  style.FontFace = Me.Font 

  style.ButtonBackColor = Button1.BackColor
  ' Initialize addtional properties...
End Sub

4. In each of your form loads, assign values from the preferences class:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As EventArgs) _
  Handles MyBase.Load

  Dim style As StylePreferences = New StylePreferences
  Me.BackColor = style.FrmBackColor
  Me.ForeColor = style.FrmTextColor
  Me.Font = style.FontFace

  Button1.BackColor = style.ButtonBackColor
  Button2.BackColor = style.ButtonBackColor
  ' Initialize addtional properties...

End Sub

Notice that you do not have to assign every property on every control if you assign the form level ones first. This will act all the controls on the form, as is the case with the Font in this sample.

Elizabeth Gee, 11 January 2005



Page view counter