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
{
[CommandMethod("COLTXT")]
static public void CreateColouredMText()
{
Document doc =
Application.DocumentManager.MdiActiveDocument;
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 =
db.TransactionManager.StartTransaction();
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} " +
"{\\C5;multi-}{\\C6;coloured}\\P";
// Open the block table, the model space and
// add our MText
BlockTable bt =
(BlockTable)tr.GetObject(
db.BlockTableId,
OpenMode.ForRead
);
BlockTableRecord ms =
(BlockTableRecord)tr.GetObject(
bt[BlockTableRecord.ModelSpace],
OpenMode.ForWrite
);
mtId = ms.AppendEntity(mt);
tr.AddNewlyCreatedDBObject(mt, true);
// Finally we commit our transaction
tr.Commit();
}
}
}
}
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:
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.