VB 2010 save and load Color Dialog

2k views Asked by At

I am working on a program that contains saved user preferences. I the program a user can set a color and it will be saved to use again. However, try as I might their is no way after hours of work that I've found to save a System.Drawing.Event ARGB to a string of Integer to save as a file.

The code below shows my most successful attempt I can get the hex conversion to work but cannot succeed in returning it to ARGB

    Dim color As New ColorDialog
    Dim userpref As String = ColorTranslator.ToHtml(color.Color)
    Dim readcolor As Color = ColorTranslator.FromHtml(userpref)
    If (color.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
        Button1.BackColor = Drawing.Color.FromArgb(readcolor)
    End If

When trying to convert to Strings or Integers usually I just get random numbers that aren't what I want or Color [Black] for every color please help!

2

There are 2 answers

0
Dano On BEST ANSWER

Try using the ColorConverter Class.

Private colorConv As New ColorConverter

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim color As New ColorDialog
    Dim userpref As String
    Dim readcolor As Color

    If (color.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
        userpref = colorConv.ConvertToString(color.Color)
        readcolor = colorConv.ConvertFromString(userpref)
        Button1.BackColor = readcolor
    End If
End Sub
0
Idle_Mind On

You're attempting to use the selected color from the dialog before it's been shown to the user, thus the random colors. Move the code that converts to a string and back to within the If block (and after the dialog has been displayed) and it should be fine:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim color As New ColorDialog
    If color.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim userpref As String = ColorTranslator.ToHtml(color.Color)
        Debug.Print("userpref = " & userpref)
        Dim readcolor As Color = ColorTranslator.FromHtml(userpref)
        Button1.BackColor = readcolor
    End If
End Sub