Persisting Colors and Other Settings with Visual Basic

Introduction

Persisting information means to save information (of any type) and to retrieve it from the location to which it has been saved. With today’s article, I will show you two ways to save colors. Now, the first question that pops into your head might be: Why? Well, the answer is simple. People like saving settings such as the location and size of a particular form, but they also like to save colours. This just adds a little professional touch in rounding off your application.

Persistence

As I mentioned earlier, persistence means to save and retrieve information. Where can you save information? Anywhere on the computer… No, that is a sick joke—because that is obviously not what you meant. You can save information in the system Registry, or, you can use the built-in Application Settings of your application. Obviously, there may be more, but this article serves only as an introduction, or a nudge in the right direction. 

Registry

The Registry stores lots of application settings. This is usually small pieces of text (actually any data, but up to a point) that would be senseless dedicating a whole file to it. For more information regarding the Registry, have a look through this (very old) article of mine.

Application.Settings

Application settings is a nice little handy storage space also for small pieces of data. This has become the preferred method to store user-specific or even application-specific settings.

Our Project

The purpose of today’s project is simply to store a color value into either the Registry or Application.Settings. There isn’t much of a design. For interest’s sake, design your Form in your Windows Forms application to resemble Figure 1.

Colors1
Figure 1: Our Design

Add a ColorDialog to your project as well.

Before I continue to the code, I must first show you how to set up your Applications.Settings. Don’t worry; it is really not complicated at all. There are two ways:

  • Through the use of the Properties Window
  • Through Project properties

Properties Window

To add a custom setting, such as a color, follow these steps:

  1. Select the form.
  2. Open the Properties Window, if not already open, by pressing F4.
  3. Expand the ApplicationSettings item on top of the Properties list.
  4. Click the ellipses button next to PropertyBinding. This will show the following screen:Colors2
    Figure 2: Property Binding
  5. Select BackColor from this list, and click the blue New link that is displayed.
  6. Give it a name, scope, and a default value, such as shown in Figure 3.Colors3
    Figure 3: Closeting
  7. Click OK.
  8. Notice the BackColor Property inside the Properties Window. This indicates that it is a custom application setting, and that the color you see in design time might not be the color you will see when the app starts because it relies on the color specified by the user.Colors4
    Figure 4: BackColor property

Project Properties

To Add a setting through the Project Properties, follow these steps:

  1. Click Project.
  2. Click Project Name Properties—where Project name is your project’s name.
  3. Click Settings.
  4. Fill in a Name, Type, and the setting as shown in Figure 5:Colors5
    Figure 5: Project Properties

Code

Let’s get down to business!

Although due to the fact that you have already set the BackColor property in Application.Settings, it will be saved automatically, but sometimes you will need to load the saved setting, especially when a user is involved. Add the next code behind the Button1 Click event:

Private Sub button1_Click(sender As Object, _
   e As EventArgs) Handles Button1.Click

   Dim ColSet As New Color

   ColSet = My.Settings.ColorSettings
   Me.BackColor = ColSet

End Sub

This code simply loads the color that was stored and makes the form’s backcolor the saved color.

Add the following code:

Private Sub Button3_Click(sender As Object, e As EventArgs) _
   Handles Button3.Click

   If (ColorDialog1.ShowDialog() = _
      Windows.Forms.DialogResult.OK) Then
      Me.BackColor = ColorDialog1.Color
      Application.UserAppDataRegistry.SetValue _
         ("Colour", ColorDialog1.Color)
   End If

End Sub

Now, let’s play with the Registry.

Add the following code:

Private Sub Button3_Click(sender As Object, e As EventArgs) _
   Handles Button3.Click

   If (ColorDialog1.ShowDialog() = _
      Windows.Forms.DialogResult.OK) Then
      Me.BackColor = ColorDialog1.Color
      Application.UserAppDataRegistry.SetValue("Colour", _
         ColorDialog1.Color)
   End If

End Sub

This saves the actual color value into the Registry. This is not the name; this is the physical color value. Now, don’t let the preceding code fool you. Loading it from the Registry is not as easy, as in the next code segment:

Private Sub button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
   'REGISTRY

   Dim strCol As [String]
   Dim blnLoaded As Boolean = False
   Dim colStoredColor As Color
   Dim A As [String] = ""
   Dim R As [String] = ""
   Dim G As [String] = ""
   Dim B As [String] = ""
   Dim strLength As Integer
   strCol = Application.UserAppDataRegistry.GetValue _
      ("Colour").ToString()
   Dim strColorName As [String] = ""

   Dim ArrColor As [String]()

   ArrColor = strCol.Split(",".ToCharArray())

   A = strStringRight(ArrColor(0), _
      ArrColor(0).IndexOf("=") + 1)
   R = strStringRight(ArrColor(1), _
      ArrColor(1).IndexOf("=") + 1)
   G = strStringRight(ArrColor(2), _
      ArrColor(2).IndexOf("=") + 1)

   strLength = ArrColor(3).Length - _
      ArrColor(3).LastIndexOf("]")

   B = strPartRight(ArrColor(3), _
      ArrColor(3).IndexOf("=") + 1, strLength)

   blnLoaded = True

   If blnLoaded = True Then

      colStoredColor = _
         System.Drawing.Color.FromArgb(Convert.ToInt16(A), _
         Convert.ToInt16(R), Convert.ToInt16(G), _
         Convert.ToInt16(B))
      Else

      colStoredColor = Color.FromName(strColorName)
   End If

   Me.BackColor = colStoredColor
End Sub

This code basically reads the color value. Then, it breaks the string apart with the use of the following two functions (which is just a simpler way of breaking strings apart with SubString):

Public Shared Function strStringRight(strInput As String, _
   intStart As Integer) As String

   Dim result As String = strInput.Substring(intStart)

   Return result
End Function

Public Shared Function strPartRight(strInput As String, _
   intStart As Integer, intLength As Integer) As String

   Dim result As String = _
      strInput.Substring(intStart, intLength)

   Return result
End Function

As I mentioned, the original string gets broken up. It basically gets the Alpha, Red, Green, and Blue values. Once all those values have been read, it is easy to assemble the physical color again via the use of the built-in Convert.ToInt16 methods.

I have attached a working sample.

Conclusion

I hope you have enjoyed today’s article. Until next time, cheers!

About the Author

Hannes du Preez is a Microsoft MVP for Visual Basic for the seventh year in a row.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read