Through the Interface: Creating an AutoCAD MText object containing different colours using .NET

May 2015

Sun Mon Tue Wed Thu Fri Sat
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30


« Changing the layer of an entity in an AutoCAD block using .NET | Main | Allowing interactive dragging of a selection of AutoCAD objects using .NET »

June 07, 2010

Creating an AutoCAD MText object containing different colours using .NET

Some weeks ago we received this question via ADN support:

My string contains several sentences and I need to make 2 of these sentences Red. I know that I could use a separate Mtext for the red portion; however, I was wondering if there was a way to programatically do this using just one Mtext?

A big thanks to Varadarajan Krishnan, from our DevTech team in India, for providing the code that formed the basis for the below solution. I decided to spice things up slightly by adding some additional per-phrase and per-word colouring.

Here’s the C# code:

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.Geometry;


namespace MTextCreation


  public class Commands



    static public void CreateColouredMText()


      Document doc =


      Database db = doc.Database;

      Editor ed = doc.Editor;


      // Variables for our MText entity's identity

      // and location


      ObjectId mtId;

      Point3d mtLoc = Point3d.Origin;


      Transaction tr =


      using (tr)


        // Create our new MText and set its properties


        MText mt = new MText();

        mt.Location = mtLoc;

        mt.Contents =

          "Some text in the default colour...\\P" +

          "{\\C1;Something red}\\P" +

          "{\\C2;Something yellow}\\P" +

          "{\\C3;And} {\\C4;something} " +



        // Open the block table, the model space and

        // add our MText


        BlockTable bt =






        BlockTableRecord ms =






        mtId = ms.AppendEntity(mt);

        tr.AddNewlyCreatedDBObject(mt, true);


        // Finally we commit our transaction







All very simple stuff… using the formatting codes in the Contents property the COLTXT command creates an MText entity with per-phrase – and, at times, per-word – colouring:

Multi-coloured multi-line text

In the next post we’ll look at a somewhat more interactive approach to positioning this text, which could ultimately be applied to the positioning of any object in the current user coordinate system.

blog comments powered by Disqus


10 Random Posts