Solved

Reconvert from Color.ToString() back to a Color

Posted on 2008-06-14
12
2,310 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Setting ACL permissions after creating user with DC replication lag possible? 5 39
c# string handling 1 27
Error in page 3 45
Turn on intranet settings 1 37
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

911 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

16 Experts available now in Live!

Get 1:1 Help Now