This question came in from Limin as a comment in this previous post:
Is there .Net interface for autocad command "DrawOrder"? For example: after solid-hatch a polyline, need to reorder polyline and hatch, how to make it happen using .NET?
I've put together some C# code to demonstrate how to do this:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
namespace HatchDrawOrder
{
public class Commands
{
[CommandMethod("HDO")]
static public void HatchDrawOrder()
{
Document doc =
Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
// Ask the user to select a hatch boundary
PromptEntityOptions opt =
new PromptEntityOptions(
"\nSelect boundary: "
);
opt.SetRejectMessage("\nObject must be a curve.");
opt.AddAllowedClass(typeof(Curve), false);
PromptEntityResult res =
ed.GetEntity(opt);
if (res.Status == PromptStatus.OK)
{
Transaction tr =
doc.TransactionManager.StartTransaction();
using (tr)
{
// Check the entity is a closed curve
DBObject obj =
tr.GetObject(
res.ObjectId,
OpenMode.ForRead
);
Curve cur = obj as Curve;
if (cur != null && cur.Closed == false)
{
ed.WriteMessage("\nLoop must be a closed curve.");
}
else
{
// Add the hatch to the model space
BlockTable bt =
(BlockTable)tr.GetObject(
doc.Database.BlockTableId,
OpenMode.ForRead
);
BlockTableRecord btr =
(BlockTableRecord)tr.GetObject(
bt[BlockTableRecord.ModelSpace],
OpenMode.ForWrite
);
Hatch hat = new Hatch();
hat.SetDatabaseDefaults();
hat.SetHatchPattern(
HatchPatternType.PreDefined,
"SOLID"
);
ObjectId hatId = btr.AppendEntity(hat);
tr.AddNewlyCreatedDBObject(hat, true);
// Add the hatch loop and complete the hatch
ObjectIdCollection ids =
new ObjectIdCollection();
ids.Add(res.ObjectId);
hat.Associative = true;
hat.AppendLoop(
HatchLoopTypes.Default,
ids
);
hat.EvaluateHatch(true);
// Change the draworder of both hatch and loop
btr.DowngradeOpen();
ids.Add(hatId);
DrawOrderTable dot =
(DrawOrderTable)tr.GetObject(
btr.DrawOrderTableId,
OpenMode.ForWrite
);
dot.MoveToBottom(ids);
tr.Commit();
}
}
}
}
}
}
The code to manipulate the draw order of these two entities is very simple - we have to open the DrawOrderTable for the space containing the entities we care about, and use it to change the order in which the entities are drawn. In this case I chose to send them both to the back of the draw order stack, but you might also manipulate their draw order relative to other entities in the drawing.
On a personal note, my family and I have arrived safely in Beijing - we're all a bit jet-lagged, but very happy to be here. The journey was thankfully uneventful, and with two young children that's really as much as you can hope for. :-)