Friday, August 12, 2016

Showing Current Selection in a Modeless Form

There is a question post in the AutoCAD .NET discussion forum here. I happened to have a similar requirement in one of my recent development projects. So, instead of post a reply in the discussion forum there, I though it would be easier to post a relatively simple and run-able project for the benefit of all readers.

The project is fairly easy and is comprised of 3 classes.

Class CurrentSelectionWatcher:

using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
namespace ShowSelectionChange
{
    public class CurrentSelectionWatcher
    {
        private frmSelection _view = null;
        private bool _show = false;
        private Document _curDoc = null;
        public CurrentSelectionWatcher()
        {
            _curDoc = CadApp.DocumentManager.MdiActiveDocument;
            if (_curDoc != null)
            {
                SetView();
                _curDoc.ImpliedSelectionChanged += 
                    Document_ImpliedSelectionChanged;
            }
 
            CadApp.DocumentManager.DocumentBecameCurrent += 
                DocumentManager_DocumentBecameCurrent;
        }
 
        public bool IsShown
        {
            get { return _show; }
        }
 
        private void Document_ImpliedSelectionChanged(
            object sender, EventArgs e)
        {
            SetView();
        }
        
        private void DocumentManager_DocumentBecameCurrent(
            object sender, DocumentCollectionEventArgs e)
        {
            if (_curDoc!=null)
            {
                _curDoc.ImpliedSelectionChanged -= 
                    Document_ImpliedSelectionChanged;
            }
 
            if (e.Document!=null)
            {
                if (e.Document != _curDoc)
                {
                    ClearView();
                    SetView();
                    _curDoc = e.Document;
                    _curDoc.ImpliedSelectionChanged += 
                        Document_ImpliedSelectionChanged;
                }
            }
        }
 
        public void Show()
        {
            _view = new frmSelection();
            _view.VisibleChanged += _view_VisibleChanged;
            CadApp.ShowModelessDialog(_view);
            _show = true;
        }
 
        private void _view_VisibleChanged(object sender, EventArgs e)
        {
            if (!_view.Visible)
            {
                _view.Dispose();
                _view = null;
                _show = false;
            }
        }
 
        #region private methods
 
        private void ClearView()
        {
            _view.ClearView();
        }
 
        private void SetView()
        {
            if (!_show) return;
            if (!_curDoc.IsActive) return;
            
            var res = _curDoc.Editor.SelectImplied();
            if (res.Status==PromptStatus.OK)
            {
                _view.SetSelection(res.Value.GetObjectIds());
            }
            else
            {
                _view.ClearView();
            }
        }
 
        #endregion
    }
}

Then a Windows.Form class frmSelection:



This form contains a ListView, a Button and a Label.

Here is the code-behind:
using System;
using System.Windows.Forms;
 
using Autodesk.AutoCAD.DatabaseServices;
 
namespace ShowSelectionChange
{
    public partial class frmSelection : Form
    {
        public frmSelection()
        {
            InitializeComponent();
 
            ClearView();
        }
 
        public void ClearView()
        {
            lvSelection.Items.Clear();
            lblCount.Text = "Selected: 0";
        }
 
        public void SetSelection(ObjectId[] entIds)
        {
            ClearView();
 
            foreach (var id in entIds)
            {
                var item = new ListViewItem(id.ToString());
                item.SubItems.Add(id.ObjectClass.DxfName);
                item.Selected = false;
 
                lvSelection.Items.Add(item);           
            }
 
            lblCount.Text = "Selected: " + 
                lvSelection.Items.Count.ToString();
        }
 
        private void btnClose_Click(object sender, EventArgs e)
        {
            Visible = false;
        }
    }
}

And finally, here the the CommandClass that runs the code:
using Autodesk.AutoCAD.Runtime;
 
[assemblyCommandClass(typeof(ShowSelectionChange.Commands))]
 
namespace ShowSelectionChange
{
    public class Commands
    {
        private static CurrentSelectionWatcher _selectionCounter = null;
 
        [CommandMethod("WatchSelection"CommandFlags.Session)]
        public static void DoSessionCommand()
        {
            if (_selectionCounter==null)
            {
                _selectionCounter = new CurrentSelectionWatcher();
            }
 
            if (!_selectionCounter.IsShown) _selectionCounter.Show();
        }
    }
}

Here is a video clip shows how the code works.

Obviously, I can make the floating form as static and only show/hide it instead of creating new instance/disposing. Of course the modeless form can be substituted by a PaletteSet easily.

P.S. When I copied the code a few hours ago, I missed a couple of lines, which actually makes the execution appear having a bug. The missing lines has been added (in red). I also missed the link to the video clip.

Extra Code

In the following discussion on the topic in AutoCAD .NET API forum, the OP asked if I could show sample code with a PaletteSet. So, here are some extra codee, working in this manner:

  • When only one entity is selected/highlighted, and the entity is a lightweight polyline, a floating PaletteSet with single palette shows the polyline's information;
  • When more than one entities are selected, or no entity is selected, the PaletteSet hides automatically.
The codes are as following.

First, I created another selection watching class CurrentSelectionWatcherA.cs:

using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.DatabaseServices;
 
namespace ShowSelectionChange
{
    public class CurrentSelectionWatcherA
    {
        private MyPolylinePaletteSet _ps = null;
        private Document _curDoc = null;
 
        public CurrentSelectionWatcherA()
        {
            _ps = new MyPolylinePaletteSet();
 
            _curDoc = CadApp.DocumentManager.MdiActiveDocument;
            if (_curDoc != null)
            {
                SetView();
                _curDoc.ImpliedSelectionChanged += 
                    Document_ImpliedSelectionChanged;
            }
 
            CadApp.DocumentManager.DocumentBecameCurrent += 
                DocumentManager_DocumentBecameCurrent;
        }
 
        private void Document_ImpliedSelectionChanged(
            object sender, EventArgs e)
        {
            SetView();
        }
        
        private void DocumentManager_DocumentBecameCurrent(
            object sender, DocumentCollectionEventArgs e)
        {
            if (_curDoc!=null)
            {
                _curDoc.ImpliedSelectionChanged -= 
                    Document_ImpliedSelectionChanged;
            }
 
            if (e.Document!=null)
            {
                if (e.Document != _curDoc)
                {
                    SetView();
                    _curDoc = e.Document;
                    _curDoc.ImpliedSelectionChanged += 
                        Document_ImpliedSelectionChanged;
                }
            }
        }
 
        #region private methods
 
        private void SetView()
        {
            if (!_curDoc.IsActive)
            {
                _ps.Visible = false;
                return;
            }
 
            ObjectId polyId = ObjectId.Null;
            var res = _curDoc.Editor.SelectImplied();
            if (res.Status==PromptStatus.OK)
            {
                if (res.Value.Count==1)
                {
                    var id = res.Value[0].ObjectId;
                    if (id.ObjectClass.DxfName.ToUpper()=="LWPOLYLINE")
                    {
                        polyId = id;
                    }
                }            
            }
            
            if (polyId.IsNull)
            {
                _ps.Visible = false;
            }
            else
            {
                _ps.ShowPolyline(polyId);
                _ps.Visible = true;
            }
        }
 
        #endregion
    }
}

Secondly, here is the PaletteSet class MyPolylinePaletteSet.cs:

using System;
using System.Drawing;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Windows;
 
namespace ShowSelectionChange
{
    public class MyPolylinePaletteSet : PaletteSet
    {
        private PolylinePalette _palette = null;
 
        public MyPolylinePaletteSet():
            base("My Polyline","",new Guid("D07DBD90-4D4C-44DB-A6C4-3CC030BD0520"))
        {
            Style = PaletteSetStyles.UsePaletteNameAsTitleForSingle;
            DockEnabled = DockSides.None;
            Dock = DockSides.None;
            Size = new Size(300, 200);
            MinimumSize = new Size(300, 200);
 
            _palette = new PolylinePalette();
            Add("My Polyline", _palette);
        }
 
        public void ShowPolyline(ObjectId polyId)
        {
            string id = "";
            string len = "";
 
            using (var tran = polyId.Database.TransactionManager.StartTransaction())
            {
                var poly = tran.GetObject(polyId, OpenMode.ForRead) as Polyline;
                if (poly!=null)
                {
                    id = polyId.ToString();
                    len = poly.Length.ToString("########0.000");
                }
 
                _palette.ShowData(id, len);
            }
        }
    }
}

This is the UserControl used as single Palette: PolylinePalette.cs:




using System.Windows.Forms;
 
namespace ShowSelectionChange
{
    public partial class PolylinePalette : UserControl
    {
        public PolylinePalette()
        {
            InitializeComponent();
        }
 
        public void ShowData(string id, string length)
        {
            txtId.Text = id;
            txtLength.Text = length;
        }
    }
}

Finally, this is the CommandClass that run the code (the red code is for this addition):


using Autodesk.AutoCAD.Runtime;
 
[assemblyCommandClass(typeof(ShowSelectionChange.Commands))]
 
namespace ShowSelectionChange
{
    public class Commands
    {
        private static CurrentSelectionWatcher _selectionCounter = null;
        private static CurrentSelectionWatcherA _polyWatcher = null;
 
        [CommandMethod("WatchSelection"CommandFlags.Session)]
        public static void WatchImpliedSelection()
        {
            if (_selectionCounter==null)
            {
                _selectionCounter = new CurrentSelectionWatcher();
            }
 
            _selectionCounter.Show();
        }
 
        [CommandMethod("ShowPoly"CommandFlags.Session)]
        public static void WatchSelectedPolyline()
        {
            if (_polyWatcher==null)
            {
                _polyWatcher = new CurrentSelectionWatcherA();
            }
        }
    }
}

Now see this video clip for the action.

If one wants to let the PaletteSet stay or docked whether there is single polyline selected or not, the code can be easily modified to do that.

The technique shown here can be used as dynamic entity information tip, similar to QuickProperties Window (well, not as pretty).





Sunday, May 22, 2016

Highlight Attributes in BlockReference: Revisit

Well, it has been long since my last post, because I have been very busy at work for quite a while. My Marathon training/running started a couple of years ago takes my time out of work more and more, thus it is difficult to find an hour or two to sit writing, even though there are quite some topics on AutoCAD programming interesting me: my busy work recently is mostly related to AutoCAD programming.

The Topic

In one of my programming task, I need to find a way to provide user a good workflow to allow user to edit block attribute. The target blocks are complicated title blocks with attributes scattered all over the drawing layout, the data used for the attribute could come from back end  data sources, or entered by user, or it could be set by back end data source as default value and then edited by user manually.

Since user data entry is required, a custom data entry UI is used, instead of using AutoCAD built-in attribute editing mechanism. I also want AutoCAD automatically zooms to and highlights the attribute when user edits an attribute in the custom UI.

I did have an article on highlighting attribute in BlockReference here. However, in that post, it is about highlighting all attribute in a BlockRefernce, while in my current need, it is hightlight attribute one at a time. I also want to have my own way of "highlight" instead of AutoCAD's highlight, which is not that eye-catching if the drawing layout is crowded. This time, I want to use a bounding frame surrounding the target attribute, which results in a bit extra code to compute the bounding frame's corner points, if the attribute's rotation is not 0.0.

In the aforementioned article, I used transient graphics to do the highlight, but also mentioned I could have done it with Overrule. Now that I have a chance to do a similar thing, I decided to give both a try.

The Code

Here is the code of using Transient Graphic:

using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.GraphicsInterface;
 
namespace ViewAttributeDrawOverrule
{
    public class AttributeHighlighter
    {
        private TransientManager _tm = TransientManager.CurrentTransientManager;
        private CadDb.Polyline _poly = null;
 
        public void SetAttributeHighlight(ObjectId attId, int colorIndex=2)
        {
            if (_poly!=null)
            {
                ClearAttributeHighlight();
            }
 
            using (var tran = attId.Database.TransactionManager.StartTransaction())
            {
                var att = (AttributeReference)tran.GetObject(attId, OpenMode.ForRead);
                _poly = MiscHelper.GetTextBoundingBox(att, colorIndex);
                tran.Commit();
            }
 
            if (_poly!=null)
            {
                MiscHelper.ZoomTo(attId);
                _tm.AddTransient(
                    _poly, 
                    TransientDrawingMode.DirectTopmost, 
                    128, 
                    new IntegerCollection());
            }
        }
 
        public void ClearAttributeHighlight()
        {
            if (_poly == nullreturn;
            _tm.EraseTransient(_poly, new IntegerCollection());
            _poly.Dispose();
            _poly = null;
 
            CadApp.DocumentManager.MdiActiveDocument.Editor.UpdateScreen();
        }
    }
}

Here is the code of using DrawableOverrule:

using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.GraphicsInterface;
 
namespace ViewAttributeDrawOverrule
{
    public class AttributeDrawOverrule : DrawableOverrule
    {
        private ObjectId _targetAttId = ObjectId.Null;
        private static AttributeDrawOverrule _instance = null;
        private bool _overruling = false;
        private bool _started = false;
 
        private AttributeDrawOverrule()
        {
 
        }
 
        public static AttributeDrawOverrule Instance
        {
            get
            {
                if (_instance==null)
                {
                    _instance = new AttributeDrawOverrule();
                }
 
                return _instance;
            }
        }
 
        public bool Started
        {
            get { return _started; }
        }
 
        public void Start()
        {
            _overruling = Overrule.Overruling;
 
            _targetAttId = ObjectId.Null;
 
            AddOverrule(RXClass.GetClass(typeof(AttributeReference)), thistrue);
            SetCustomFilter();
 
            _started = true;
            Overrule.Overruling = true;
 
            CadApp.DocumentManager.MdiActiveDocument.Editor.Regen();
        }
 
        public void Stop()
        {
            RemoveOverrule(RXClass.GetClass(typeof(AttributeReference)), this);
            Overrule.Overruling = _overruling;
            _started = false;
 
            CadApp.DocumentManager.MdiActiveDocument.Editor.Regen();
        }
        
        public void SetOverruledAttribute(ObjectId attributeId, bool zoomTo=false)
        {
            if (zoomTo) MiscHelper.ZoomTo(attributeId);
            _targetAttId = attributeId;
            CadApp.DocumentManager.MdiActiveDocument.Editor.Regen();
        }
 
        public override bool IsApplicable(RXObject overruledSubject)
        {
            if (_targetAttId.IsNull) return false;
 
            DBObject obj = overruledSubject as DBObject;
            if (obj!=null)
            {
                return obj.ObjectId == _targetAttId;
            }
            else
            {
                return false;
            }
        }
 
        public override bool WorldDraw(Drawable drawable, WorldDraw wd)
        {
            Entity ent = drawable as Entity;
            AttributeReference att = ent as AttributeReference;
 
            Point3dCollection pts = MiscHelper.GetTextBoundingBox(att);
 
            FillType oldFillType = wd.SubEntityTraits.FillType;
            wd.SubEntityTraits.FillType = FillType.FillNever;
 
            short oldColor = wd.SubEntityTraits.Color;
            wd.SubEntityTraits.Color = (short)2;
 
            wd.Geometry.Polygon(pts);
 
            wd.SubEntityTraits.FillType = oldFillType;
            wd.SubEntityTraits.Color = oldColor;
 
            return base.WorldDraw(drawable, wd);
        }
    }
}

In both of the above 2 classes, a helper class MiscHelper is used:

using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
namespace ViewAttributeDrawOverrule
{
    public class MiscHelper
    {
        public static Point3dCollection GetTextBoundingBox(DBText txt)
        {
            Point3dCollection pts = new Point3dCollection();
 
            if (txt.Rotation != 0.0)
            {
                Point3d basePt = txt.AlignmentPoint;
 
                using (var clone = txt.Clone() as Entity)
                {
                    var mt = Matrix3d.Rotation(0 -txt.Rotation, Vector3d.ZAxis, basePt);
                    clone.TransformBy(mt);
                    var ext = clone.GeometricExtents;
                    ext = EnlargeExtents(ext, 1.5);
 
                    Point3d maxPt = ext.MaxPoint;
                    Point3d minPt = ext.MinPoint;
 
                    using (var poly = new Autodesk.AutoCAD.DatabaseServices.Polyline(4))
                    {
                        poly.AddVertexAt(0, new Point2d(minPt.X, minPt.Y), 0.0, 0.0, 0.0);
                        poly.AddVertexAt(0, new Point2d(minPt.X, maxPt.Y), 0.0, 0.0, 0.0);
                        poly.AddVertexAt(0, new Point2d(maxPt.X, maxPt.Y), 0.0, 0.0, 0.0);
                        poly.AddVertexAt(0, new Point2d(maxPt.X, minPt.Y), 0.0, 0.0, 0.0);
 
                        poly.Closed = true;
 
                        var mt1 = Matrix3d.Rotation(txt.Rotation, Vector3d.ZAxis, basePt);
                        poly.TransformBy(mt1);
 
                        for (int i = 0; i < poly.NumberOfVertices; i++)
                        {
                            Point3d pt = poly.GetPoint3dAt(i);
                            pts.Add(pt);
                        }
                    }
                }
            }
            else
            {
                Extents3d ext = txt.GeometricExtents;
                ext = EnlargeExtents(ext, 1.5);
 
                Point3d maxPt = ext.MaxPoint;
                Point3d minPt = ext.MinPoint;
 
 
                pts.Add(new Point3d(minPt.X, minPt.Y, minPt.Z));
                pts.Add(new Point3d(minPt.X, maxPt.Y, minPt.Z));
                pts.Add(new Point3d(maxPt.X, maxPt.Y, minPt.Z));
                pts.Add(new Point3d(maxPt.X, minPt.Y, minPt.Z));
            }
 
            return pts;
        }
 
        public static Polyline GetTextBoundingBox(DBText txt, int boundColor)
        {
            Point3dCollection pts = GetTextBoundingBox(txt);
 
            var poly = new Polyline(pts.Count);
            int index = 0;
            foreach (Point3d pt in pts)
            {
                poly.AddVertexAt(index, new Point2d(pt.X, pt.Y), 0.0, 1.0, 1.0);
                index++;
            }
 
            poly.ColorIndex = boundColor;
            poly.Closed = true;
 
            return poly;
        }
 
        public static void ZoomTo(ObjectId attId)
        {
            Point3d pt1, pt2;
 
            using (var tran = attId.Database.TransactionManager.StartTransaction())
            {
                var ent = (Entity)tran.GetObject(attId, OpenMode.ForRead);
                pt1 = ent.GeometricExtents.MinPoint;
                pt2 = ent.GeometricExtents.MaxPoint;
                tran.Commit();
            }
 
            double h = pt2.Y - pt1.Y;
            double w = pt2.X - pt1.X;
            double l = h;
            if (w > h) l = w;
 
 
            double[] p1 = new double[] { pt1.X - l / 2.0, pt1.Y - l / 2.0, pt1.Z };
            double[] p2 = new double[] { pt2.X + l / 2.0, pt2.Y + l / 2.0, pt2.Z };
 
            dynamic comApp = CadApp.AcadApplication;
            comApp.ZoomWindow(p1, p2);
        }
 
        #region private methods
 
        private static Extents3d EnlargeExtents(Extents3d ext, double factor)
        {
            Extents3d ex;
            if (factor > 1.0)
            {
                double h = (ext.MaxPoint.Y - ext.MinPoint.Y);
                var delt = (h * factor - h) / 2.0;
 
                var minP = new Point3d(
                    ext.MinPoint.X - delt, ext.MinPoint.Y - delt, ext.MinPoint.Z);
                var maxP = new Point3d(
                    ext.MaxPoint.X + delt, ext.MaxPoint.Y + delt, ext.MaxPoint.Z);
 
                ex = new Extents3d(minP, maxP);
            }
            else
            {
                ex = new Extents3d(ext.MinPoint, ext.MaxPoint);
            }
 
            return ex;
        }
 
        #endregion
    }
}

To test the 2 classes, I created a small dialog box with a DatagridView on it to list all attribute of a selected block. The form is very simple and can be seen in the video clip. The UI is only meant for showing how an target attribute is highlighted in AutoCAD when it is selected in a custom UI (dialog box, in this case). Here is the the form's code-behind:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
 
using Autodesk.AutoCAD.DatabaseServices;
 
namespace ViewAttributeDrawOverrule
{
    public partial class dlgBlock : Form
    {
        private AttributeDrawOverrule _overrule =
            AttributeDrawOverrule.Instance;
        private AttributeHighlighter _highlighter = null;
        private bool _useHighlighter = false;
 
        public dlgBlock()
        {
            InitializeComponent();
        }
 
        public void SetData(
            string blkName, 
            ObjectId blkId, 
            IEnumerable<Tuple<ObjectIdstring>> attributeData,
            bool useHighlighter=false)
        {
            _useHighlighter = useHighlighter; 
 
            Text = "Attributes in Block - " + blkName;
            LoadDataGrid(attributeData);
 
            if (_useHighlighter)
            {
                _highlighter = new AttributeHighlighter();
            }
            else
            {
                _overrule.Start();
            }
        }
 
        private void LoadDataGrid(IEnumerable<Tuple<ObjectIdstring>> attributeData)
        {
            System.Data.DataTable tbl = CreateBindingTable(attributeData);
            dgAttributes.DataSource = tbl;   
        }
 
        private System.Data.DataTable CreateBindingTable(
            IEnumerable<Tuple<ObjectIdstring>> attributeData)
        {
            var tbl = new System.Data.DataTable();
 
            System.Data.DataColumn col;
 
            col = new System.Data.DataColumn("Id"typeof(ObjectId));
            tbl.Columns.Add(col);
 
            col = new System.Data.DataColumn("Tag"typeof(string));
            tbl.Columns.Add(col);
 
            col = new System.Data.DataColumn("View"typeof(string));
            tbl.Columns.Add(col);
 
            foreach (var tup in attributeData)
            {
                var row = tbl.NewRow();
                row["Id"] = tup.Item1;
                row["Tag"] = tup.Item2;
                row["View"] = "View/Zoom";
 
                tbl.Rows.Add(row);
            }
 
            return tbl;
        }
 
        private void ViewAttribute(ObjectId attId)
        {
            if (_useHighlighter)
            {
                _highlighter.ClearAttributeHighlight();
                _highlighter.SetAttributeHighlight(attId);
            }
            else
            {
                _overrule.SetOverruledAttribute(attId, true);
            }
        }
 
        private void dgAttributes_CellContentClick(
            object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex==2)
            {
                ObjectId attId = (ObjectId)dgAttributes.Rows[e.RowIndex].Cells[0].Value;
                ViewAttribute(attId);
            }
        }
 
        private void btnClose_Click(object sender, EventArgs e)
        {
            if (_useHighlighter)
            {
                _highlighter.ClearAttributeHighlight();
            }
            else
            {
                _overrule.Stop();
            }
 
            this.DialogResult = DialogResult.OK;
        }
    }
}

This is the command class that puts all together to do the work:

using System;
using System.Collections.Generic;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
[assemblyCommandClass(typeof(ViewAttributeDrawOverrule.MyCadCommands))]
 
namespace ViewAttributeDrawOverrule
{
    public class MyCadCommands
    {
        [CommandMethod("OvAtt")]
        public static void OverruleAttribute()
        {
            Document dwg = CadApp.DocumentManager.MdiActiveDocument;
            Editor ed = dwg.Editor;
 
            try
            {
                string blkName;
                ObjectId blkId;
                List<Tuple<ObjectIdstring>> attData;
                if (GetBlockAttributes(dwg, out blkName, out blkId, out attData))
                {
                    ShowForm(blkName, blkId, attData);
                }
                else
                {
                    ed.WriteMessage("\n*Cancel*");
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: {0}\n{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
            }
        }
 
        [CommandMethod("HlAtt")]
        public static void HighlightAttribute()
        {
            Document dwg = CadApp.DocumentManager.MdiActiveDocument;
            Editor ed = dwg.Editor;
 
            try
            {
                string blkName;
                ObjectId blkId;
                List<Tuple<ObjectIdstring>> attData;
                if (GetBlockAttributes(dwg, out blkName, out blkId, out attData))
                {
                    ShowForm(blkName, blkId, attData, true);
                }
                else
                {
                    ed.WriteMessage("\n*Cancel*");
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: {0}\n{1}", ex.Message, ex.StackTrace);
            }
            finally
            {
                Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
            }
        }
 
        private static bool GetBlockAttributes(
            Document dwg, 
            out string blkName, 
            out ObjectId blkId, 
            out List<Tuple<ObjectId,string>> attributeData)
        {
            blkName = "";
            blkId = ObjectId.Null;
            attributeData = new List<Tuple<ObjectIdstring>>();
 
            var opt = new PromptEntityOptions(
                "\nSelect a block with attribute:");
            opt.SetRejectMessage("\nNot a block. Please retry.");
            opt.AddAllowedClass(typeof(BlockReference), true);
 
            var res = dwg.Editor.GetEntity(opt);
            if (res.Status == PromptStatus.OK)
            {
                using (var tran = dwg.TransactionManager.StartTransaction())
                {
                    var blk = (BlockReference)tran.GetObject(res.ObjectId, OpenMode.ForRead);
 
                    blkName = blk.Name;
                    blkId = res.ObjectId;
 
                    foreach (ObjectId id in blk.AttributeCollection)
                    {
                        var att = (AttributeReference)tran.GetObject(id, OpenMode.ForRead);
                        attributeData.Add(
                            new Tuple<ObjectIdstring>(id, att.Tag + ": " + att.TextString));
                    }
 
                    tran.Commit();
                }
 
                return true;
            }
            else
            {
                return false;
            }
        }
 
        private static void ShowForm(
            string blkName, ObjectId blkId, 
            IEnumerable<Tuple<ObjectId,string>> attData, 
            bool useHighlighter=false)
        {
            using (var dlg = new dlgBlock())
            {
                dlg.Top = 50;
                dlg.Left = 50;
 
                dlg.SetData(blkName, blkId, attData, useHighlighter);
                CadApp.ShowModalDialog(CadApp.MainWindow.Handle, dlg, false);
            }
        }
    }
}

Click this video link to see the code in action.

Further Interests

In terms of providing visual aid to AutoCAD user, both Transient Graphics and Overrule used here do the job as expected, at least with the simple drawing example.

However, we can see that the code of using Transient Graphics is much simpler than of Overrule. And more importantly, with Overrule, Editor.Regen() needs to be called frequently, which could be an issue (slowness) if the drawing has heavy layout that takes time to Regen (usually title blocks are on PaperSpace layout, which is not that difficult to Regen as ModelSpace, though).

Also, if I really wanted to have both approaches to be used in my current development and to be re-used in future development, I could have had an interface with 2 methods - ZoomTo(ObjectId) and SetAttributeHightlight(ObjectId), and then implement this interface with Transient Graphics and DrawableOverrule. Since I have already decided using Transient Graphics is simple enough and good enough, there is no need to use Overrule for my production development.

Source code can be downloaded here (Visual Studio 2015 and AutoCAD 2016).

Followers

About Me

My photo
After graduating from university, I worked as civil engineer for more than 10 years. It was AutoCAD use that led me to the path of computer programming. Although I now do more generic business software development, such as enterprise system, timesheet, billing, web services..., AutoCAD related programming is always interesting me and I still get AutoCAD programming tasks assigned to me from time to time. So, AutoCAD goes, I go.