Color manipulation

Annorax

Member
Joined
Aug 31, 2007
Messages
12
Location
MA, USA
Programming Experience
1-3
Hi everyone,

I'm working on a text editor and I want the ability to save the Foreground and Background colors. I've been trying to find a way to save the colors to a file and upon startup, read them and set them.

I have getHexColor and hexToColor methods as follows:

VB.NET:
	Private Function GetHexColor(colorObj as System.Drawing.Color) as String
		return "#" & Hex(colorObj.R) & Hex(colorObj.G) & Hex(colorObj.B)
	End Function

	Public Function HexToColor(ByVal hexString As String) As Color
	
	    Try
	      Dim r, g, b As Integer
	
	      hexString = hexString.Replace("#", Nothing)
	     If Not hexString.Length = 6 Then
	      Return Color.Black
	      End If
	
	      r = HexToInt(hexString.Substring(0, 2))
	      g = HexToInt(hexString.Substring(2, 2))
	      b = HexToInt(hexString.Substring(4, 2))
	
	      Return Color.FromArgb(255, r, g, b)
	   Catch ex As Exception
	      Debug.WriteLine(ex.ToString)	
	      Return Color.Black
	    End Try
	
	  End Function

	Private Function HexToInt(ByVal hexString As String) As Int32
    	Return Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber, Nothing)
  	End Function

However, the getHexColor method does not always save to 6 characters and the hexToColor method expects it to, resulting in usually black being returned.

I'm pretty new at this, but is there an easy way to convert colors to strings and vice versa?

Thanks for any help. :)
 
Use the ColorTranslator.ToHtml/.FromHtml methods.
 
Back
Top