Solved

Reconvert from Color.ToString() back to a Color

Posted on 2008-06-14
12
2,295 Views
Last Modified: 2013-12-17
I have used a Color Dialog to set a Color and save it in an ini file with colorDialog1.Color.ToString().

This produces results like:
BackColor=Color [Red]  // if "Known" or
BackColor=Color [A=255, R=255, G=255, B=128] // light yellow

I do NOT want to restrict things to "Known Colors".

When reading the ini file, how do I easily convert "BackColor" into a real "Color"?.

I cannot find a "FromString()" method.  (VS C# 2008 Express)

Thanks,
Phil
0
Comment
Question by:PHenningsen
  • 6
  • 5
12 Comments
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 21786896
You can use the ColorTranslator.ToHtml method http://msdn.microsoft.com/en-us/library/system.drawing.colortranslator.tohtml.aspx to save the Color object to the ini file and the ColorTranslator.FromHtml method http://msdn.microsoft.com/en-us/library/system.drawing.colortranslator.fromhtml.aspx to recreate the Color object after reading the value from the ini file

You will need: using System.Drawing;

This article might be useful as well http://devintelligence.com/blogs/netadventures/archive/2005/11/28/1124.aspx
0
 

Author Comment

by:PHenningsen
ID: 21786947
This seems wierd.

1) There is no HTML anything in my program.  Why would I have to use an HTML method?  (I was just getting to like C#).

2) I'm using MS, VS C# 2008 Express.  The Properties > Application > Target Framework = ".Net Framework 3.5"  Yet, in my program, System.Environment.Version returns "2.0.50727.1433".  And the help for "ColorTranslator.ToHtml" says it works for .NET 3.5.  What's up here?

(I do have .NET 3.5 installed, I think)

Thanks,
Phil
0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 21787043
ColorTranslator object's ToHtml is just a means to serialize the Color object to a string and FromHtml to deserialize and reconstruct the Color object, think of it as ToString and FromString if you like. It will work with .NET Framework versions below 3.5 as well, below is sample code that worked on my end and I don't have .NET Framework 3.5 installed:
Color myColor = new Color();
 

myColor = Color.AliceBlue;
 

string myColorSerialized = System.Drawing.ColorTranslator.ToHtml(myColor);
 

MessageBox.Show("Color serialized is: " + myColorSerialized);
 

Color deserializedColor = System.Drawing.ColorTranslator.FromHtml(myColorSerialized);
 

MessageBox.Show("Deserialized color is" + deserializedColor.ToString());

Open in new window

0
 

Author Comment

by:PHenningsen
ID: 21787056
I am getting the error:  (on your code above and on my code)
Error      1      'System.Drawing.Color' does not contain a definition for 'ToHtml' and no extension method 'ToHtml' accepting a first argument of type 'System.Drawing.Color' could be found (are you missing a using directive or an assembly reference?)      C:\Personal\Projects\Utilities\Tele\TelConfig.cs      407      61      Tele
0
 

Author Comment

by:PHenningsen
ID: 21787067
And, yes, I have
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 21787068
At the top of your file, do you have the following line?

using System.Drawing;
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 19

Expert Comment

by:LordOfPorts
ID: 21787077
I am not certain, the error states 'System.Drawing.Color' does not contain a definition, just to confirm you are using 'System.Drawing.ColorTranslator' i.e. ColorTranslator and not Color followed by .ToHtml?
0
 

Author Comment

by:PHenningsen
ID: 21787119
using System.Drawing.ColorTranslator;
produces
Error      1      A using namespace directive can only be applied to namespaces; 'System.Drawing.ColorTranslator' is a type not a namespace      C:\Personal\Projects\Utilities\Tele\TelConfig.cs      7      7      Tele

The actual code is:
    private void btnColor_Click(object sender, EventArgs e)
    {
      int iX;
      if (colorDialog1.ShowDialog() != DialogResult.Cancel)
      {
        iX = listBoxFont.FindString("BackColor=");
        listBoxFont.Items.RemoveAt(iX);

        Color myColor = new Color();

        //myColor = Color.AliceBlue;
        //string myColorSerialized = System.Drawing.ColorTranslator.ToHtml(myColor);
        //MessageBox.Show("Color serialized is: " + myColorSerialized);
        //Color deserializedColor = System.Drawing.ColorTranslator.FromHtml(myColorSerialized);
        //MessageBox.Show("Deserialized color is" + deserializedColor.ToString());

        myColor = colorDialog1.Color();
        listBoxFont.Items.Insert(iX, "BackColor=" + myColor.ToHtml());       //?? .ToHTML / .ToString ??
        //if (colorDialog1.Color.IsKnownColor)
        //  listBoxFont.Items.Insert(iX,"BackColor=" + colorDialog1.Color.ToKnownColor());
        //else
        //  listBoxFont.Items.Insert(iX,"BackColor=" + colorDialog1.Color.ToArgb());
        listBoxFont.Tag = "Yes";                          // indicates Changed
        listBoxFont.BackColor = colorDialog1.Color;
      }
    }

One the line:
myColor = colorDialog1.Color();

I get:
Error      1      Non-invocable member 'System.Windows.Forms.ColorDialog.Color' cannot be used like a method.      C:\Personal\Projects\Utilities\Tele\TelConfig.cs      401      32      Tele

And on the next line (with ToHMTL) the Error is:
Error      1      Non-invocable member 'System.Windows.Forms.ColorDialog.Color' cannot be used like a method.      C:\Personal\Projects\Utilities\Tele\TelConfig.cs      401      32      Tele

My problem here is that I do not want to restrict the colors to "Known Colors"






0
 
LVL 62

Expert Comment

by:Fernando Soto
ID: 21787347
Hi PHenningsen;

Instead of saving the color the way you did, "colorDialog1.Color.ToString()", save it as a string this way

String BackColor = colorDialog1.Color.ToArgb().ToString();

This will result in a signed integer value that represents the ARGB of the color selected. then to get it back to a color object you can do this

Color ArgbColor = Color.FromArgb(Int32.Parse(BackColor));

Fernando
0
 
LVL 19

Accepted Solution

by:
LordOfPorts earned 500 total points
ID: 21789026
You can remove the "using System.Drawing.ColorTranslator;" at the top, only "using System.Drawing;" is needed.

Below is also your code with few corrections, I have verified that it works:
private void btnColor_Click(object sender, EventArgs e)

        {

            int iX;

            if (colorDialog1.ShowDialog() != DialogResult.Cancel)

            {

                iX = listBoxFont.FindString("BackColor=");

                listBoxFont.Items.RemoveAt(iX);
 

                Color myColor = new Color();
 

                //myColor = Color.AliceBlue;

                //string myColorSerialized = System.Drawing.ColorTranslator.ToHtml(myColor);

                //MessageBox.Show("Color serialized is: " + myColorSerialized);

                //Color deserializedColor = System.Drawing.ColorTranslator.FromHtml(myColorSerialized);

                //MessageBox.Show("Deserialized color is" + deserializedColor.ToString());
 

                myColor = colorDialog1.Color;

                listBoxFont.Items.Insert(iX, "BackColor=" + System.Drawing.ColorTranslator.ToHtml(myColor));       //?? .ToHTML / .ToString ??

                //if (colorDialog1.Color.IsKnownColor)

                //  listBoxFont.Items.Insert(iX,"BackColor=" + colorDialog1.Color.ToKnownColor());

                //else

                //  listBoxFont.Items.Insert(iX,"BackColor=" + colorDialog1.Color.ToArgb());

                listBoxFont.Tag = "Yes";                          // indicates Changed

                listBoxFont.BackColor = colorDialog1.Color;

            }

        }

Open in new window

BackColor.png
0
 
LVL 19

Expert Comment

by:LordOfPorts
ID: 21789052
It will not limit you to selecting just known colors, below are example screenshots, you can define a custom color and save it.
SelectCustomColor.png
CustomColorApplied.png
0
 

Author Closing Comment

by:PHenningsen
ID: 31467266
Not your fault, I guess, but I do not consider this solution as "elegant".

Is #FFFF80 better than -128 or [R=FF, G=FF, B=80].  Frankly, I prefer the latter.

Why is System.Drawing.ColorTranslator.ToHtml(myColor); different syntax than Color.ToHtml()?

Oh, well, nothing is perfect.
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now