Friday, December 16, 2016

PaletteSet/Modeless Form And Non-Drawing Document Window

Since AutoCAD 2015, Autodesk added non-document window in AutoCAD. It was called "New" tab, in AutoCAD 2015, and then was changed to "Start" tab. Further more, one or more custom non-drawing document windows can be added through custom code. My work place still uses AutoCAD 2015 and for certain reason our default setup is to disable "New" tab, and we does not have any non-drawing document window created by our customization code. So, it was only recently I found out the new AutoCAD feature of non-drawing document window causes trouble to some of our existing CAD applications, namely those using custom PaletteSet or modeless form.

As we know, when using floating window (PaletteSet/modeless form) with AutoCAD, if the content showing on the UI is tied to drawing, the content should be updated whenever user switch active drawing (Application.DocumentManager.MdiActiveDocument). When user closes all drawing in AutoCAD, the UI should disappear. Below is the code that has been working well when AutoCAD did not have "New" or "Start" tab/window (i.e. pre-AutoCAD 2015 versions):

Class MyPaletteSet:
using System;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
namespace HidePaletteSet
{
    public class MyPaletteSet : PaletteSet
    {
        private MyPalette _palette;
        private string _dwgName = "";
        private bool _preZeroDocVisible = false;
 
        public MyPaletteSet():base(
            "My PaletteSet",""new Guid("593F9149-F6F7-4771-BDF0-552A3BF6C4F0"))
        {
            MinimumSize = new System.Drawing.Size(500, 300);
 
            _palette = new HidePaletteSet.MyPalette();
            Add("My Palette", _palette);
 
            CadApp.DocumentManager.DocumentBecameCurrent += 
                DocumentManager_DocumentBecameCurrent;
            CadApp.DocumentManager.DocumentDestroyed += 
                DocumentManager_DocumentDestroyed;
 
        }
 
        public void Show()
        {
            if (!Visible)
            {
                var name = CadApp.DocumentManager.MdiActiveDocument.Name;
                if (name.ToUpper()!=_dwgName.ToUpper())
                {
                    UpdateMyPaletteView();
                }
            }
 
            Visible = true;
            Size = new System.Drawing.Size(500, 300);
            DockEnabled = DockSides.None;
            Dock = DockSides.None;
        }
 
        #region private methods
 
        private void DocumentManager_DocumentDestroyed(
            object sender, DocumentDestroyedEventArgs e)
        {
            if (CadApp.DocumentManager.Count <= 1)
            {
                _preZeroDocVisible = Visible;
                Visible = false;
                _dwgName = "";
            }        
        }
 
        private void DocumentManager_DocumentBecameCurrent(
            object sender, DocumentCollectionEventArgs e)
        {
            if (string.IsNullOrEmpty(_dwgName) && _preZeroDocVisible)
            {
                // A document is added/opened from 0 document status
                // and since the paletteset is visible before
                // entering 0 document status, thus make it visible.
                Visible = true;
            }
 
            if (Visible)
            {
                if (e.Document.Name.ToUpper() != _dwgName.ToUpper())
                {
                    _dwgName = e.Document.Name;
                    UpdateMyPaletteView();
                }
            }
        }
 
        private void UpdateMyPaletteView()
        {
            var fileName = CadApp.DocumentManager.MdiActiveDocument.Name;
            _palette.DrawingFileName = fileName;
        }
 
        #endregion
    }
}

The UserControl as palette is a simple UserControl with one Label and one read-only TextBox on it:
using System.Windows.Forms;
 
namespace HidePaletteSet
{
    public partial class MyPalette : UserControl
    {
        public MyPalette()
        {
            InitializeComponent();
        }
 
        public string DrawingFileName
        {
            set { txtFileName.Text = value; }
        }
    }
}

And here is the command class:
using Autodesk.AutoCAD.Runtime;
 
[assemblyCommandClass(typeof(HidePaletteSet.Commands))]
 
namespace HidePaletteSet
{
    public class Commands
    {
        private static MyPaletteSet _myPS = null;
 
        [CommandMethod("MyPS"CommandFlags.Session)]
        public static void RunSessionCommand()
        {
            if (_myPS==null)
            {
                _myPS = new HidePaletteSet.MyPaletteSet();
            }
 
            _myPS.Show();
        }
    }
}

This video clip shows how the code runs as expected when there is no "New"/"Start" window in AutoCAD. Because I use AutoCAD 2017, I simply set the system variable "STARTMODE" to 0 to disable "START" window.

Now, let me run the same code with "START" window enabled. See this video clip. As the video clip shows, with the PaletteSet is visible when I switch AutoCAD's active window from drawing document window to a non-drawing document window, an "null object" exception is raised, which crashes AutoCAD.

It turns out that when AutoCAD's active window switches from drawing window to non-drawing window (be it AutoCAD built-in "Start" window, or a custom non-drawing window), the event DocumentCollection_DocumentBecameCurrent still fires, but the Document property of the event argument is null, thus the not handled exception crashing AutoCAD. So, in the DocumentCollection.DocumentBecameCurrent event handler, I modified the code (actually added a few lines of code, in red color) to handle the case of Document being null:

private void DocumentManager_DocumentBecameCurrent(
    object sender, DocumentCollectionEventArgs e)
{
    if (e.Document==null)
    {
        _preZeroDocVisible = Visible;
        _dwgName = "";
        Visible = false;
        return;
    }
 
    if (string.IsNullOrEmpty(_dwgName) && _preZeroDocVisible)
    {
        // A document is added/opened from 0 document status
        // and since the paletteset is visible before
        // entering 0 document status, thus make it visible.
        Visible = true;
    }
 
    if (Visible)
    {
        if (e.Document.Name.ToUpper() != _dwgName.ToUpper())
        {
            _dwgName = e.Document.Name;
            UpdateMyPaletteView();
        }
    }
}

Now see this video clip that shows the PaletteSet now shows and hides correctly.

Obviously, when new features being added into AutoCAD, it could break existing custom applications. In this particular case, Autodesk chose to still fire an DocumentCollection event - DocumentBecameCurrent, which was meant for a drawing document, when a non-drawing document becomes active, and oddly enough, the document that is supposed to become current is null.

Of course, my modified code works with pre-2015 AutoCAD where no non-document window available, because the Document property in the event argument would never be null, so the added code (in red) would never be executed.





Sunday, November 27, 2016

Getting Outline of Overlapped Entities

Sometimes, in a drawing there are some entities overlapping on each other, for example, a few closed polylines. How do we find out a closed polyline that is the outline of these overlapped polygons?

This picture shows 3 polygons overlapping each other:



This picture shows the outline (in red) we want to obtain:



In this article, to simplify the code and the discussion, let me limit the entities are all closed Polylines, and each Polyline overlaps with at least 1 other Polyline (so that a continuous outline can be formed); also I only care to get an exterior outline and ignore possible islands inside the outline. Obviously, I should expect to obtain a Polyline, as the red outline shown in picture above, or a series of points that are the vertices of the Polyline.

How to proceed with .NET API code to do this? After some tries, I settled with these 2 steps:

1. Converting each Polyline to Region, then use Region.BooleanOperation() method to merge/unite all the closed Polylines into one single Region;

2. Use Brep API to generate a BrepEntity from the Region, then find the exterior loop of the BrepEntity. These exterior loop provides all the vertices of outline Polyline.

Here is the code that implements the thought of the process:

using System.Collections.Generic;
using System.Linq;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
 
using Autodesk.AutoCAD.BoundaryRepresentation;
 
namespace GetOutLine
{
    public class OutLiner
    {
        private Document _dwg;
 
        public OutLiner(Document dwg)
        {
            _dwg = dwg;
        }
 
        public void DrawOutline(IEnumerable<ObjectId> entIds)
        {
            using (var polyline = GetOutline(entIds))
            {
                using (var tran = _dwg.TransactionManager.StartTransaction())
                {
                    var space = (BlockTableRecord)tran.GetObject(
                        _dwg.Database.CurrentSpaceId, OpenMode.ForWrite);
                    space.AppendEntity(polyline as Entity);
                    tran.AddNewlyCreatedDBObject(polyline as Entitytrue);
                    tran.Commit();
                }
            }
        }
 
        public Entity GetOutline(IEnumerable<ObjectId> entIds)
        {
            var regions = new List<Region>();
 
            using (var tran = _dwg.TransactionManager.StartTransaction())
            {
                foreach (var entId in entIds)
                {
                    var poly = tran.GetObject(entId, OpenMode.ForRead) as Polyline;
                    if (poly!=null)
                    {
                        var rgs = GetRegionFromPolyline(poly);
                        regions.AddRange(rgs);
                    }
                    
                }
 
                tran.Commit();
            }
 
            using (var region = MergeRegions(regions))
            {
                if (region != null)
                {
                    var brep = new Brep(region);
                    var points = new List<Point2d>();
                    var faceCount = brep.Faces.Count();
                    var face = brep.Faces.First();
                    foreach (var loop in face.Loops)
                    {
                        if (loop.LoopType == LoopType.LoopExterior)
                        {
                            foreach (var vertex in loop.Vertices)
                            {
                                points.Add(new Point2d(vertex.Point.X, vertex.Point.Y));
                            }
                            break;
                        }
                    }
 
                    return CreatePolyline(points);
                }
                else
                {
                    return null;
                }
            }
        }
 
        #region private methods
 
        private List<Region> GetRegionFromPolyline(CadDb.Polyline poly)
        {
            var regions = new List<Region>();
 
            var sourceCol = new DBObjectCollection();
            var dbObj = poly.Clone() as CadDb.Polyline;
            dbObj.Closed = true;
            sourceCol.Add(dbObj);
 
            var dbObjs = Region.CreateFromCurves(sourceCol);
            foreach (var obj in dbObjs)
            {
                if (obj is Region) regions.Add(obj as Region);
            }
 
            return regions;
        }
 
        private Region MergeRegions(List<Region> regions)
        {
            if (regions.Count == 0) return null;
            if (regions.Count == 1) return regions[0];
 
            var region = regions[0];
            for (int i=1; i<regions.Count; i++)
            {
                var rg = regions[i];
                region.BooleanOperation(BooleanOperationType.BoolUnite, rg);
                rg.Dispose();
            }
 
            return region;
        }
 
        private CadDb.Polyline CreatePolyline(List<Point2d> points)
        {
            var poly = new CadDb.Polyline(points.Count());
 
            for (int i=0; i<points.Count;i++)
            {
                poly.AddVertexAt(i, points[i], 0.0, 0.3, 0.3);
            }
 
            poly.SetDatabaseDefaults(_dwg.Database);
            poly.ColorIndex = 1;
            
            poly.Closed = true;
 
            return poly;
        }
 
        #endregion
    }
}

Here is the command that makes above code in action:

using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
 
[assemblyCommandClass(typeof(GetOutLine.Commands))]
 
namespace GetOutLine
{
    public class Commands
    {
        [CommandMethod("Outline")]
        public static void RunMyCommand()
        {
            var dwg = CadApp.DocumentManager.MdiActiveDocument;
            var ed = dwg.Editor;
 
            try
            {
                var ids = SelectPolylines(ed);
                if (ids != null)
                {
                    var liner = new OutLiner(dwg);
                    liner.DrawOutline(ids);
                }
                else
                {
                    ed.WriteMessage("\n*Cancel*");
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nCommand failed:\n{0}", ex.Message);
                ed.WriteMessage("\n*Cancel*");
            }
        }
 
        private static ObjectId[] SelectPolylines(Editor ed)
        {
            var vals = new TypedValue[]
            {
                new TypedValue((int)DxfCode.Start, "LWPOLYLINE")
            };
 
            var res = ed.GetSelection(new SelectionFilter(vals));
            if (res.Status == PromptStatus.OK)
                return res.Value.GetObjectIds();
            else
                return null;
        }   
    }
}

Watch these video clip as the proof of how the code works.

Extra Thought

Obviously, creating a BrepEntity based on Region garantees a exterior loop/boundary will be generated, thus the outline curve. I could extend the Region generating process beyond Polyline entity or closed Curve (Circle,..). For example, if the entity is an Arc, I can draw a Line from the Arc's start point to its end point, then use these 2 entities to generate a Region; for DBText or MText, I can use its bounding box as a Polyline to generate the Region. But things could become very complicated if the overlapped entities could be any possible type of entities.

Oh, beside the usual 3 AutoCAD .NET API assemblies, the project needs to set reference to BREP API assembly (acdbmgdbrep.dll).












Wednesday, November 2, 2016

Extract AutoCAD Civil3D's Label Text

I have been doing much less writing on my AutoCAD programming during past 2 years, because of a). I have been quite busy at work, thus much less time I can spend on the topics I might have interest to dig in; 2). since I became master marathon runner (in my late 50!) a couple years ago, most my out-of-work time has been running, endless running (50 to 70 km/week, 4 to 6 formal races/year).

Anyway, back to AutoCAD programming. My company moved from AutoCAD Map to AutoCAD Civil3D since AutoCAD 2015 a while ago. Naturally, some custom programming task against AutoCAD Civil3D features became my job description, which exposes me to a vast new realm that I did not touch before.

Recently, I was ask to provide a way to extract Civil3D label's text. Labels in Civil3D are very powerful and complicated annotation objects. As a "newbie" Civil3D programmer, I spent quite sometime in vain to search through Civl3D's API: nothing came up to let me retrieve the displayed text string of a label.

Eventually, I found this article "Get CogoPoint Label Text" in ADN blogs "Infrastructure Modeling DevBlog", by Augosto Goncalves.

The code shown in that article worked quite well, except that if a label's text is stacked (e.g. the label text is displayed as multiple lines of text), there would be missing space between the text string segment. See this video clip.

The "missing space" issue can be easily fixed by adding a space when retrieved text string segment being combined with previously retrieved text string segment. See the the code below, which is quoted from that article with minor modification (in red):

private string GetText(ObjectId id)
{
    // store the DBTexts
    StringBuilder entityText = new StringBuilder();
 
    Database db = Application.DocumentManager.
        MdiActiveDocument.Database;
    using (Transaction trans = db.
        TransactionManager.StartTransaction())
    {
        // open the entity
        Entity point = trans.GetObject(id,
            OpenMode.ForRead) as Entity;
 
        // do a full explode (considering explode again
        // all BlockReferences and MText)
        List<DBObject> objs = FullExplode(point);
        foreach (Entity ent in objs)
        {
            // now get the text of each DBText
            if (ent.GetType() == typeof(DBText))
            {
                DBText text = ent as DBText;
                entityText.AppendLine(" " + text.TextString);
            }
        }
        trans.Commit();
    }
 
    return entityText.ToString().Trim();
}

See this video clip showing the result of modified code. I was quite happy of adopting this code in my work to allow my program retrieve Civil3D label's displayed text, well, until I ran into "curved" labels (e.g. labels used to annotate curved line work, in which the text characters are aligned along the curve) - all the spaces between text segment that make the text string read-able were gone. Actually, when running my modified code shown above, a space added between every character of the label text.

See this video clip showing the result of retrieved label text on "curved" label.

To investigate the cause, I manually did the recursive exploding of a label, as the code does, either a straight one, or curved one. The manual exploding revealed:

  • With straight label, after recursive exploding I end up with one or more DBText entities. Thus, I can combine all the DBTexts' TextString value with space in between to eventually  assemble a text string as the label's displayed text.
  • With curved string, after the recursively exploding, the label is also eventually exploded into DBText entities with each single character as a DBText, thus the resulted DBTexts effectively lose their literal meaning.
I have to say that whoever created Civil3D label, he/she must be incredibly talented and invented the way to use curved label to annotate curved entities. But how do I get the labels displayed text, so that it still conveys the same literal meaning as the label? 

It turned out a solution came out rather easily when I discuss the difficulty I was facing (with the curved label) with an experienced Civil3D user, showing how a label ends up with after repeated explode. He suggests I drag the curved label first before the attempt of retrieving label text, because dragging a curved label makes it "straight" label. So, the solution is programmtically dragging the label, retrieving the label text with recursive exploding, and then placing the dragged label back (resetting the label).

Here is the code I wrote, based Augosto's, which drags a curved label before exploding it in memory, and then place the label back (to curved style):

using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using CadDb = Autodesk.AutoCAD.DatabaseServices;
using CivilDb = Autodesk.Civil.DatabaseServices;
 
namespace WSP.GEO.UDS.Civil3dUtilities
{
    public static class LabelTextExtractor
    {
        public static string GetDisplayedLabelText(CadDb.ObjectId labelId)
        {
            if (labelId.ObjectClass.DxfName.ToUpper()!="AECC_GENERAL_SEGMENT_LABEL")
            {
                throw new ArgumentException(
                    "argument mismatch: not an \"AECC_GENERAL_SEGMENT_LABEL\"");
            }
 
            StringBuilder lblText = new StringBuilder();
 
            using (var tran=labelId.Database.TransactionManager.StartTransaction())
            {
                var label = tran.GetObject(labelId, OpenMode.ForRead) as CivilDb.Label;
                if (label!=null)
                {
                    bool changed = !label.Dragged && label.AllowsDragging;
                    try
                    {
                        if (changed)
                        {
                            label.UpgradeOpen();
                            double delta = label.StartPoint.DistanceTo(label.EndPoint);
                            label.LabelLocation = 
                                new Point3d(label.LabelLocation.X + 
                                    delta, label.LabelLocation.Y + 
                                    delta, label.LabelLocation.Z);
                        }
 
                        var dbObjs = FullExplode(label);
                        foreach (var obj in dbObjs)
                        {
                            if (obj.GetType() == typeof(DBText))
                            {
                                lblText.Append(" " + (obj as DBText).TextString);
                            }
 
                            obj.Dispose();
                        }
                    }
                    finally
                    {
                        if (changed) label.ResetLocation();
                    }
                }
 
                tran.Commit();
            }
 
            return lblText.ToString().Trim();
        }
 
        #region private methods
 
        private static List<CadDb.DBObject> FullExplode(CadDb.Entity ent)
        {
            // final result
            List<CadDb.DBObject> fullList = new List<CadDb.DBObject>();
 
            // explode the entity
            DBObjectCollection explodedObjects = new DBObjectCollection();
            ent.Explode(explodedObjects);
            foreach (CadDb.Entity explodedObj in explodedObjects)
            {
                // if the exploded entity is a blockref or mtext
                // then explode again
                if (explodedObj.GetType() == typeof(CadDb.BlockReference) ||
                    explodedObj.GetType() == typeof(CadDb.MText))
                {
                    fullList.AddRange(FullExplode(explodedObj));
                }
                else
                    fullList.Add(explodedObj);
            }
            return fullList;
        }
 
        #endregion
    }
}

As the code shows, I do not even care if the label is straight or curved. I simply test if the label is allowed to be dragged and if yes, if being dragged. If both are yes, programmatically drag it before doing the recursive explodes. Afterwards, I rest the label's location, if it has been programmatically dragged.

Here is the video clip showing the result of retrieving label's text.















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).





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.