Okay, since back in the day I struggled with MLeaders this caught my attention, Today I had some time to go back through old code and see what I did and why. This is what I came up with.
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using MLeaderTest;
using Application = Autodesk.AutoCAD.ApplicationServices.Core.Application;
[assembly
: CommandClass
(typeof(Commands
))]
namespace MLeaderTest
{
public class Commands
{
[CommandMethod("COPYMODIFYMLEADER")]
public static void CopyModifyMLeader()
{
var db = Application.DocumentManager.MdiActiveDocument.Database;
var ed = Application.DocumentManager.MdiActiveDocument.Editor;
var peo
= new PromptEntityOptions
("Pick MLeader to copy"); peo.SetRejectMessage("Pick a MLeader");
peo
.AddAllowedClass(typeof(MLeader
),
false); var per = ed.GetEntity(peo);
using (var tr = db.TransactionManager.StartTransaction())
{
var existingLeader = (MLeader)tr.GetObject(per.ObjectId, OpenMode.ForRead);
var mleader = (MLeader)existingLeader.Clone();
//Add MLeader to database before changing. AutoCAD changes text properties when you add it.
var bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
var ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
ms.AppendEntity(mleader);
tr.AddNewlyCreatedDBObject(mleader, true);
//Now make changes and Commit().
//These seem to be the only properties that you have to set post clone to get a copy that behaves the same.
{
Contents = "COPIED\\PLEADER",
TextStyleId = existingLeader.MText.TextStyleId
};
mleader.MText = mtext;
mleader.TextHeight = existingLeader.TextHeight;
mleader.TextAlignmentType = existingLeader.TextAlignmentType;
mleader.TextLocation = existingLeader.TextLocation;
tr.Commit();
}
}
}
}
This works for me even after saving and reopening the drawing. Hopefully it will be of some use to you.