As Jeff noted, applying a formatting code directly is fiddly work. That's always given me a headache.
Here's another solution that uses a TextEditor (restricting its use to 2011), that probably has its own gotchas.
public class TextCommands
{
private static double LastMTextWidth { get; set; }
static TextCommands() { TextCommands.LastMTextWidth = 1; }
[CommandMethod("ChangeMtextWidth")]
public void ChangeMtextWidth()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
PromptDoubleOptions pdo = new PromptDoubleOptions("Enter width: ");
pdo.AllowNegative = false;
pdo.AllowZero = false;
pdo.AllowNone = true;
pdo.DefaultValue = TextCommands.LastMTextWidth;
pdo.UseDefaultValue = true;
PromptDoubleResult pdr = ed.GetDouble(pdo);
if (pdr.Status != PromptStatus.OK)
{
ed.WriteMessage("Cancelled.\n");
return;
}
double width = pdr.Value;
PromptSelectionOptions pso = new PromptSelectionOptions();
pso.MessageForAdding = "Select mtexts to add: ";
pso.MessageForRemoval = "Select mtexts to remove: ";
pso.RejectObjectsOnLockedLayers = true;
pso.RejectObjectsFromNonCurrentSpace = true;
pso.AllowDuplicates = false;
SelectionFilter sf =
new SelectionFilter(new TypedValue[] {
new TypedValue((int)DxfCode.Start, "MTEXT") });
PromptSelectionResult psr = ed.GetSelection(pso, sf);
if (psr.Status != PromptStatus.OK)
{
ed.WriteMessage("Cancelled.\n");
return;
}
TextCommands.LastMTextWidth = width;
using (Transaction trx = db.TransactionManager.StartTransaction())
{
foreach (ObjectId mtId in psr.Value.GetObjectIds())
{
MText mt = trx.GetObject(mtId, OpenMode.ForWrite) as MText;
if (mt == null) continue;
using (TextEditor te = InplaceTextEditor.CreateTextEditor(mt))
{
te.SelectAll();
te.Selection.WidthScale = width;
te.Close(TextEditor.ExitStatus.ExitSave);
}
}
trx.Commit();
}
}
}