William Cruz

C# extension – System.Draw.Color to Integer

Discussion created by William Cruz on Aug 21, 2020

There’s probably a million ways to get the color you want, but I find this to be the simplest. The “formula” for this is taken directly from the sw help file – 2020 SOLIDWORKS Help - Color Parameter in Configurations , I just made an extension out of it since I use this quite often. Enjoy

 

Usage example:

_swLayerMgr.AddLayer(“layer name”, "description", Color.LimeGreen.ToSwColorCode(),

                        (int)swLineStyles_e.swLineCONTINUOUS, (int)swLineWeights_e.swLW_THICK);

 

public static int ToSwColorCode(this Color c)
    {
        try
        {
            return
                 Math.Max(Math.Min((int)c.R, 255), 0) +
                 Math.Max(Math.Min((int)c.G, 255), 0) * 16 * 16 +
                 Math.Max(Math.Min((int)c.B, 255), 0) * 16 * 16 * 16 * 16;
        }
        catch (Exception ex)
        {
            /*handle your errors*/
            return 0;
        }
    }

Outcomes