In the last post we saw code to display and use AutoCAD's built-in colour, linetype and lineweight dialogs. In this post we extend that by using each of them in sequence to display various properties of an entity, allowing the user to modify them.
While this is slightly more "real world" than the last post, it doesn't really make sense to implement a command such as the one below (the property palette is much better, for instance :-). The main purpose is to show how to set the initial values in the various dialogs and afterwards to make use of the values the user selects.
Here's the C# code:
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Windows;
namespace EntityProperties
{
public class Commands
{
[CommandMethod("SPE")]
public void SetPropertiesOnEntity()
{
Document doc =
Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
PromptEntityResult per =
ed.GetEntity(
"\nSelect entity to modify: "
);
if (per.Status != PromptStatus.OK)
return;
Transaction tr =
db.TransactionManager.StartTransaction();
using (tr)
{
Entity ent =
(Entity)
tr.GetObject(
per.ObjectId,
OpenMode.ForRead
);
ColorDialog cd = new ColorDialog();
cd.Color = ent.Color;
System.Windows.Forms.DialogResult dr;
dr = cd.ShowDialog();
if (dr != System.Windows.Forms.DialogResult.OK)
return;
LinetypeDialog ltd = new LinetypeDialog();
ltd.Linetype = ent.LinetypeId;
dr = ltd.ShowDialog();
if (dr != System.Windows.Forms.DialogResult.OK)
return;
LineWeightDialog lwd = new LineWeightDialog();
lwd.LineWeight = ent.LineWeight;
dr = lwd.ShowDialog();
if (dr != System.Windows.Forms.DialogResult.OK)
return;
ent.UpgradeOpen();
if (ent.Color != cd.Color)
ent.Color = cd.Color;
if (ent.LinetypeId != ltd.Linetype)
ent.LinetypeId = ltd.Linetype;
if (ent.LineWeight != lwd.LineWeight)
ent.LineWeight = lwd.LineWeight;
tr.Commit();
}
}
}
}
Notice that we "return" from the code in a number of places, should the user cancel one of the dialogs. This is perfectly safe, as we're "using" the transaction object, and once it leaves scope it will automatically be disposed (and therefore aborted).
Running the SPE command will display in sequence the dialogs shown in the previous post, and use the user's input to change the state of the selected entity.