Using a color-book entry to set the colour of an AutoCAD entity using .NET

Another quick post, as I'm just about to head back home after a long week in Boston. This post comes from a technical solution provided by Sreekar Devatha, from DevTech India.

I won't go into detail regarding the following code, but it should be fairly clear what's going on: from a particular colour-name it looks up a colour from a color-book (yes, I know I've used "colour" and "color" in the same sentence, but "color-book" is an AutoCAD term and it's hard for me to drop my u's when I don't have to, even after having lived in the US for a number of years... 🙂

Once it gets the colour, it then uses it to set the colour of an entity the user selects.

Here's the C# code:

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Colors;

using System;

using System.ComponentModel;

using System.Globalization;

namespace ColorBookApplication

{

  public class Commands

  {

    [CommandMethod("SC")]

    static public void SetColorToRal()

    {

      Document doc =

        Application.DocumentManager.MdiActiveDocument;

      Database db = doc.Database;

      Editor ed = doc.Editor;

      ITypeDescriptorContext typeDes = null;

      CultureInfo cult = null;

      ColorConverter conv = new ColorConverter();

      String str = "RAL CLASSIC$RAL 1000";

      Color col = null;

      try

      {

        // Retrieve color from color-book

        col =

          conv.ConvertFrom(typeDes, cult, str) as Color;

      }

      catch (System.Exception ex)

      {

        ed.WriteMessage("Exception: " + ex.Message);

      }

      if (col != null)

      {

        // Select an entity to set the retrieved color

        PromptEntityResult per =

          ed.GetEntity("Select an entity: ");

        if (per.Status == PromptStatus.OK)

        {

          Transaction tr =

            db.TransactionManager.StartTransaction();

          using (tr)

          {

            try

            {

              Entity ent =

                (Entity)tr.GetObject(

                  per.ObjectId,

                  OpenMode.ForWrite

                );

              // Set the color

              ent.Color = col;

              tr.Commit();

            }

            catch (Autodesk.AutoCAD.Runtime.Exception ex)

            {

              ed.WriteMessage("Exception: " + ex.Message);

              tr.Abort();

            }

          }

        }

      }

    }

  }

}

Leave a Reply

Your email address will not be published. Required fields are marked *