Thursday, June 20, 2013

Drag Something And Drop Into AutoCAD

Windows users are familiar with Windows Drag & Drop operation - clicking on something and holding down the left mouse button, then dragging it to somewhere and releasing the left mouse button. Many applications built for Windows adopt this mechanism, AutoCAD is no exception. For example, user can drag a drawing file (*.dwg) from Windows explorer and drop it into AutoCAD editor. As result, AutoCAD starts block inserting command.

When we do our customizing programming with AutoCAD's .NET API, we can easily create Drag & Drop feature into our custom applications. Imagine this user case: a form presenting some drawing options, such as drawing circles with different radius; user is asked to drag one option into AutoCAD editor to actually have the circle drawn.

Here is an entire set of code to do this.

The form that presents circle drawing options looks like this:


The code behind the form is as following:

    1 using System;
    2 using System.Linq;
    3 using System.Windows.Forms;
    4 
    5 namespace DragDropIntoAcad
    6 {
    7     public partial class dlgCircle : Form
    8     {
    9         public dlgCircle()
   10         {
   11             InitializeComponent();
   12         }
   13 
   14         private void LoadCircleList()
   15         {
   16             string[] circles = new string[]
   17             {
   18                 "Radius=3",
   19                 "Radius=4",
   20                 "Radius=5",
   21                 "Radius=6",
   22                 "Radius=7",
   23                 "Radius=8",
   24                 "Radius=9",
   25                 "Radius=10",
   26                 "Radius=11",
   27                 "Radius=12"
   28             };
   29 
   30             var data = from c in circles
   31                        select new {
   32                            CircleName = c,
   33                            CircleRadius = Int32.Parse(c.Substring(7))
   34                        };
   35 
   36             cboCircle.DisplayMember = "CircleName";
   37             cboCircle.ValueMember = "CircleRadius";
   38             cboCircle.DataSource = data.ToList();
   39         }
   40 
   41         private void dlgCircle_Load(object sender, EventArgs e)
   42         {
   43             LoadCircleList();
   44         }
   45 
   46         private void btnClose_Click(object sender, EventArgs e)
   47         {
   48             this.Visible = false;
   49         }
   50 
   51         private void dlgCircle_FormClosing(
   52             object sender, FormClosingEventArgs e)
   53         {
   54             e.Cancel = true;
   55             this.Visible = false;
   56         }
   57 
   58         private void lblCircle_MouseDown(object sender, MouseEventArgs e)
   59         {
   60             if (e.Button == MouseButtons.Left)
   61             {
   62                 double r = Convert.ToDouble(cboCircle.SelectedValue);
   63 
   64                 CircleDropper.DragDropCircle(lblCircle, r);
   65             }
   66         }
   67     }
   68 }

There are 2 things in the form's code to pay attention.

Firstly, I intend to show the form as modeless form, thus clicking the "Close" button, or clicking the "x" button of the form will only hide the form. In the command method where the form is called to show, the code there make sure only one instance of the form is ever created.

Secondly, the whole trick of doing "Drag & Drop" here lies in lblCircle_MouseDown() event handler. In order to separate AutoCAD functioning code with the UI code (the form code), I create a static class CircleDropper, which hides all the AutoCAD operation (of drawing circle) details away from the UI.

Here is the code for class CircleDropper, which draws the circle when something dragged from the form and dropped into AutoCAD editor:

    1 using System.Windows.Forms;
    2 using Autodesk.AutoCAD.ApplicationServices;
    3 using Autodesk.AutoCAD.DatabaseServices;
    4 using Autodesk.AutoCAD.EditorInput;
    5 using Autodesk.AutoCAD.Geometry;
    6 using Autodesk.AutoCAD.Windows;
    7 
    8 namespace DragDropIntoAcad
    9 {
   10     public static class CircleDropper
   11     {
   12         public static void DragDropCircle(
   13             System.Windows.Forms.Control ctl, double radius)
   14         {
   15             //Complete Drag & Drop operation, which mainly for getting
   16             //a point indicating where the dropping occurs
   17             CircleDropTarget dropTarget = new CircleDropTarget();
   18             Autodesk.AutoCAD.ApplicationServices.Application.
   19                     DoDragDrop(ctl, radius, DragDropEffects.Copy, dropTarget);
   20 
   21             Document dwg=Autodesk.AutoCAD.ApplicationServices.
   22                 Application.DocumentManager.MdiActiveDocument;
   23             Editor ed=dwg.Editor;
   24 
   25             Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView();
   26 
   27             //Create a circle. and then start an EntityJig to give user
   28             //a chance to accurately position the circle, or change
   29             //the circle's radius, or even cancel the operation
   30             using (dwg.LockDocument())
   31             {
   32                 using (Circle c = new Circle())
   33                 {
   34                     c.Radius = radius;
   35 
   36                     //Set circle's centre at location where mouse drag-drops at
   37                     c.Center = dropTarget.DropPoint;
   38 
   39                     CircleJig jig = new CircleJig(ed, c);
   40                     if (jig.Drag())
   41                     {
   42                         //Add the circle into drawing database
   43                         using (Transaction tran =
   44                             dwg.TransactionManager.StartTransaction())
   45                         {
   46                             BlockTableRecord space = (BlockTableRecord)
   47                                 tran.GetObject(dwg.Database.CurrentSpaceId,
   48                                 OpenMode.ForWrite);
   49 
   50                             space.AppendEntity(c);
   51                             tran.AddNewlyCreatedDBObject(c, true);
   52 
   53                             tran.Commit();
   54                         }
   55                     }
   56                 }
   57             }
   58 
   59             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
   60         }
   61     }
   62 
   63     public class CircleDropTarget : DropTarget
   64     {
   65         private Point3d _dropPoint = Point3d.Origin;
   66 
   67         public Point3d DropPoint
   68         {
   69             get { return _dropPoint; }
   70         }
   71 
   72         public override void OnDrop(System.Windows.Forms.DragEventArgs e)
   73         {
   74             //Convert windows location of mouse into AutoCAD editor's
   75             //WCS coordinate (Point3d)
   76             Document dwg = Autodesk.AutoCAD.ApplicationServices.
   77                 Application.DocumentManager.MdiActiveDocument;
   78 
   79             System.Drawing.Point pt = new System.Drawing.Point(e.X, e.Y);
   80             _dropPoint = dwg.Editor.PointToWorld(pt);
   81         }
   82     }
   83 
   84     public class CircleJig : EntityJig
   85     {
   86         private enum DragFor
   87         {
   88             Location=0,
   89             Radius=1,
   90         }
   91 
   92         private Editor _ed;
   93         private DragFor _dragFor = DragFor.Location;
   94         private Point3d _basePoint;
   95 
   96         private Point3d _currCentre;
   97         private double _currRadius;
   98         private Circle _circle;
   99 
  100         public CircleJig(Editor ed, Circle circle):base(circle)
  101         {
  102             _ed = ed;
  103             _circle = (Circle)this.Entity;
  104 
  105             _basePoint = _circle.Center;
  106         }
  107 
  108         public bool Drag()
  109         {
  110             while (true)
  111             {
  112                 _basePoint = _circle.Center;
  113 
  114                 _currCentre = _circle.Center;
  115                 _currRadius = _circle.Radius;
  116 
  117                 PromptResult res = _ed.Drag(this);
  118                 if (res.Status == PromptStatus.OK)
  119                 {
  120                     return true;
  121                 }
  122                 else if (res.Status == PromptStatus.Keyword)
  123                 {
  124                     switch(res.StringResult.ToUpper())
  125                     {
  126                         case "LOCATION":
  127                             _dragFor = DragFor.Location;
  128                             break;
  129                         case "RADIUS":
  130                             _dragFor = DragFor.Radius;
  131                             break;
  132                         default:
  133                             return false;
  134                     }
  135                 }
  136                 else
  137                 {
  138                     return false;
  139                 }
  140             }
  141         }
  142 
  143         protected override bool Update()
  144         {
  145             return true;
  146         }
  147 
  148         protected override SamplerStatus Sampler(JigPrompts prompts)
  149         {
  150             SamplerStatus status;
  151 
  152             switch (_dragFor)
  153             {
  154                 case DragFor.Location:
  155                     status = CircleLocationSampler(prompts);
  156                     break;
  157                 case DragFor.Radius:
  158                     status = CircleRadiusSampler(prompts);
  159                     break;
  160                 default:
  161                     status = SamplerStatus.NoChange;
  162                     break;
  163             }
  164 
  165             return status;
  166         }
  167 
  168         protected SamplerStatus CircleLocationSampler(JigPrompts prompts)
  169         {
  170             SamplerStatus status = SamplerStatus.NoChange;
  171 
  172             JigPromptPointOptions opt = new JigPromptPointOptions(
  173                 "\nPick circle centre point:");
  174             opt.AppendKeywordsToMessage = true;
  175             opt.UseBasePoint = true;
  176             opt.BasePoint = _basePoint;
  177             opt.Cursor = CursorType.RubberBand;
  178             opt.UserInputControls = UserInputControls.NullResponseAccepted;
  179             opt.Keywords.Add("Radius");
  180             opt.Keywords.Add("Cancel");
  181             opt.Keywords.Default = "Cancel";
  182 
  183             PromptPointResult res = prompts.AcquirePoint(opt);
  184             if (res.Status == PromptStatus.OK)
  185             {
  186                 _currCentre = res.Value;
  187                 if (_currCentre != _circle.Center)
  188                 {
  189                     ChangeCircleLocation();
  190                     status = SamplerStatus.OK;
  191                 }
  192             }
  193             else
  194             {
  195                 status = SamplerStatus.Cancel;
  196             }
  197 
  198             return status;
  199         }
  200 
  201         protected SamplerStatus CircleRadiusSampler(JigPrompts prompts)
  202         {
  203             SamplerStatus status = SamplerStatus.NoChange;
  204 
  205             JigPromptDistanceOptions opt = new JigPromptDistanceOptions(
  206                 "\nPick/enter circle radius:");
  207             opt.AppendKeywordsToMessage = true;
  208             opt.UseBasePoint = true;
  209             opt.BasePoint = _basePoint;
  210             opt.Cursor = CursorType.RubberBand;
  211             opt.UserInputControls =
  212                 UserInputControls.NullResponseAccepted |
  213                 UserInputControls.NoZeroResponseAccepted |
  214                 UserInputControls.NoNegativeResponseAccepted;
  215             opt.Keywords.Add("Location");
  216             opt.Keywords.Add("Cancel");
  217             opt.Keywords.Default = "Cancel";
  218 
  219             PromptDoubleResult res = prompts.AcquireDistance(opt);
  220             if (res.Status == PromptStatus.OK)
  221             {
  222                 _currRadius = res.Value;
  223                 if (_currRadius != _circle.Radius)
  224                 {
  225                     ChangeCircleRadius();
  226                     status = SamplerStatus.OK;
  227                 }
  228             }
  229             else
  230             {
  231                 status = SamplerStatus.Cancel;
  232             }
  233 
  234             return status;
  235         }
  236 
  237         private void ChangeCircleLocation()
  238         {
  239             Matrix3d mt = Matrix3d.Displacement(
  240                 _circle.Center.GetVectorTo(_currCentre));
  241             _circle.TransformBy(mt);
  242         }
  243 
  244         private void ChangeCircleRadius()
  245         {
  246             _circle.Radius = _currRadius;
  247         }
  248     }
  249 }

From the code we can see, Autodesk.AutoCAD.ApplicationServices.Application.DoDragDrop() is the key method that gets some information on what and where something is dropped into AutoCAD, which needs an argument of Autodesk.AutoCAD.Windows.DropTarget type. Since DropTarget is an abstract class, we must derive our own custom DropTarget class, hence the CircleDropTarget class here.

In most cases, only OnDrop() method in the DropTarget class is needed to be overridden, and the primary goal of that method is to obtain a point where the dropping occurs. While it is doable that in this method we add code to let AutoCAD actually draw what we want (circle, in my case), it is desired to separate entity generating code from this OnDrop() method, as my code shows.

It is also obvious that when dragging something into AutoCAD, the mouse cursor location is not ideal to accurate drafting/CAD operation. It would be good practice that once the mouse cursor is dragged into AutoCAD and dropped, user is asked to select a point in standard AutoCAD manner, better yet, user is given a sort of Jig to dynamically pick or enter accurate location, and the change for other possible operation options, including cancelling the Drag & Drop operation. All AutoCAD users know when a drawing file is dragged from Windows Explorer and dropped into AutoCAD starts "INSERT" command with a block inserting jig. This the reason of my code using an EntityJig after Drag & Drop.

OK, here is the last piece of code that runs the code:

    1 using Autodesk.AutoCAD.ApplicationServices;
    2 using Autodesk.AutoCAD.EditorInput;
    3 using Autodesk.AutoCAD.Runtime;
    4 
    5 [assembly: CommandClass(typeof(DragDropIntoAcad.MyCommands))]
    6 
    7 namespace DragDropIntoAcad
    8 {
    9     public class MyCommands
   10     {
   11         private static dlgCircle dlg=null;
   12 
   13         [CommandMethod("DragDrop")]
   14         public static void RunMyCommand()
   15         {
   16             Document dwg = Application.DocumentManager.MdiActiveDocument;
   17             Editor ed = dwg.Editor;
   18 
   19             if (dlg == null)
   20             {
   21                 dlg = new dlgCircle();
   22             }
   23 
   24             Application.ShowModelessDialog(dlg);
   25 
   26             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
   27         }
   28     }
   29 }

As usual, this video clip shows how the code works.

Personally, I do not there is much difference between dragging something from a form/tool palette into AutoCAD and clicking a ribbon/menu/toolbar item in terms of creating new entity. But, hey, if you use it properly in your custom application, your user may like it.

Friday, April 12, 2013

How to Get Current View Size

Sometimes one could run into question that you are sure you knew the answer and had dealt with it before, but just could not get it off your head right away.

A few days ago when I update an existing CAD application, I was asked to select certain entities visible in current view, be them in modelspace layout or paperspace layout, or in a active viewport of paperspace layout. I thought, "OK, I can get the size of current view and then select everything in a window that is the size of the current view (or slightly smaller than the view size). Then I went on searching Object Browser in Visual Studio for View, Viewport, ViewTableRecord, ViewportTableRecord... to see how I can easily get the size of current view in AutoCAD.

Well, it turned out that it would be unnecessarily complicated if I tried to use these classes for this task and luckily I recalled in my old VBA code I used AutoCAD system variables for similar work: VIEWSIZE and VIEWCTR.

System variable VIEWCTR provides a Point3d value as current view's centre point, while VIEWSIZE is the height of current view, measured in drawing unit. The problem left is how to know the width of current view? Again, another system variable SCREENSIZE comes to rescue: it provides the current viewport's size, but in PIXELs. Here what the unit of the size from SCREENSIZE is does not matter, we can use the ratio of width-height to calculate the current view's width in drawing unit from its height, like this:

view_width=view_height * (screen_width/screen_height)

The other thing to be careful is that the view's centre from VIEWCTR is in UCS coordinate.

Here is the code to get current view's size and its extents:

    1 using Autodesk.AutoCAD.ApplicationServices;
    2 using Autodesk.AutoCAD.DatabaseServices;
    3 using Autodesk.AutoCAD.Geometry;
    4 
    5 namespace GetViewSize
    6 {
    7     public class ViewUtil
    8     {
    9         private Document _dwg;
   10 
   11         public ViewUtil(Document dwg)
   12         {
   13             _dwg = dwg;
   14         }
   15 
   16         public Point2d GetCurrentViewSize()
   17         {
   18             //Get current view height
   19             double h = (double)Application.GetSystemVariable("VIEWSIZE");
   20 
   21             //Get current view width,
   22             //by calculate current view's width-height ratio
   23             Point2d screen = (Point2d)Application.GetSystemVariable("SCREENSIZE");
   24             double w = h * (screen.X / screen.Y);
   25 
   26             return new Point2d(w, h);
   27         }
   28 
   29         public Extents2d GetCurrentViewBound(
   30             double shrinkScale=1.0, bool drawBoundBox=false)
   31         {
   32             //Get current view size
   33             Point2d vSize = GetCurrentViewSize();
   34 
   35             double w = vSize.X * shrinkScale;
   36             double h = vSize.Y * shrinkScale;
   37 
   38 
   39             //Get current view's centre.
   40             //Note, the centre point from VIEWCTR is in UCS and
   41             //need to be transformed back to World CS
   42             Point3d cent = ((Point3d)Application.GetSystemVariable("VIEWCTR")).
   43                 TransformBy(_dwg.Editor.CurrentUserCoordinateSystem);
   44 
   45             Point2d minPoint = new Point2d(cent.X - w / 2.0, cent.Y - h / 2.0);
   46             Point2d maxPoint = new Point2d(cent.X + w / 2.0, cent.Y + h / 2.0);
   47 
   48             if (drawBoundBox)
   49             {
   50                 DrawBoundBox(minPoint, maxPoint);
   51             }
   52 
   53             return new Extents2d(minPoint, maxPoint);
   54         }
   55 
   56         private void DrawBoundBox(Point2d minPoint, Point2d maxPoint)
   57         {
   58             using (Transaction tran = _dwg.TransactionManager.StartTransaction())
   59             {
   60                 //Get current space
   61                 BlockTableRecord space = (BlockTableRecord)tran.GetObject(
   62                     _dwg.Database.CurrentSpaceId, OpenMode.ForWrite);
   63 
   64                 //Create a polyline as bounding box
   65                 Polyline pl = new Polyline(4);
   66 
   67                 pl.AddVertexAt(0, minPoint, 0.0, 0.0, 0.0);
   68                 pl.AddVertexAt(1, new Point2d(minPoint.X, maxPoint.Y), 0.0, 0.0, 0.0);
   69                 pl.AddVertexAt(2, maxPoint, 0.0, 0.0, 0.0);
   70                 pl.AddVertexAt(3, new Point2d(maxPoint.X, minPoint.Y), 0.0, 0.0, 0.0);
   71                 pl.Closed = true;
   72 
   73                 pl.SetDatabaseDefaults(_dwg.Database);
   74 
   75                 space.AppendEntity(pl);
   76                 tran.AddNewlyCreatedDBObject(pl, true);
   77 
   78                 tran.Commit();
   79             }
   80         }
   81     }
   82 }

In the GetCurrentViewBound() method, the optional argument "shrinkScale" is used for getting a slight smaller bound than the view is (or slightly larger, if it is greater than 1.0). The second optional argument is mostly for debugging purpose: if set to "true", a polyline would be drawn as the bounding box of the current view.

Here is the command class to run the code:

    1 using Autodesk.AutoCAD.ApplicationServices;
    2 using Autodesk.AutoCAD.EditorInput;
    3 using Autodesk.AutoCAD.Geometry;
    4 using Autodesk.AutoCAD.Runtime;
    5 
    6 [assembly: CommandClass(typeof(GetViewSize.MyCommands))]
    7 
    8 namespace GetViewSize
    9 {
   10     public class MyCommands
   11     {
   12         [CommandMethod("GetViewSize")]
   13         public static void RunMyCommand()
   14         {
   15             Document dwg = Application.DocumentManager.MdiActiveDocument;
   16             Editor ed = dwg.Editor;
   17 
   18             ViewUtil util = new ViewUtil(dwg);
   19 
   20             try
   21             {
   22                 //Get current view size
   23                 Point2d vSize = util.GetCurrentViewSize();
   24                 ed.WriteMessage("\nCurrent view size: " +
   25                     "H={0} W={1}", vSize.Y, vSize.X);
   26 
   27                 //Draw a bound box of current view, which
   28                 //is slightly smaller than current view
   29                 util.GetCurrentViewBound(0.95, true);
   30 
   31                 //Draw a bound box of current view, which
   32                 //is exactly the same size as current view
   33                 util.GetCurrentViewBound(1.0, true);
   34             }
   35             catch (System.Exception ex)
   36             {
   37                 ed.WriteMessage("\nError: {0}", ex.ToString());
   38             }
   39 
   40             Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
   41         }
   42     }
   43 }
 
 The code can be used to get current view's size. When in tiled multi-viewport modelspace, the view is the view in active viewport. When in paperspace layout, if there is no paperspace viewport active (after command "PS"), the view is the view of paperspace, while if there is a paperspace viewport active (after command "MS"), the view is the modelspace view seeing through the paperspace viewport.

Well, with paperspace viewport, one can use the size of the viewport and transform to size in modelspace in order to get the model view size seeing through the paperspace viewport. If the paperspace viewport has non-rectangular border, then the simple approach to get a rectangular view size shown in this article would be problematic (when the purpose is to selecting all entities visible in the view/viewport.

 

Thursday, March 14, 2013

Update - Custom Double-Click Action Using Application.BeginDoubleClick Event

I posted an article a few months ago on the topic of using Application.BeginDoubleClick event to define our own custom double-click action here.

There a discussion in Autodesk's .NET forum revealed that there is an issue which causes my solution does not work: if the double clicked entity is a BlockReference with attributes in it, the Editor.SelecctImplied() method returns PromptStatus.Error.

I tend to think this is a bug in AutoCAD managed API. Whether it is a bug or not, this is serious blow to the logic of my solution of doing custom double-click action, because BlockReference with attributes in it could be the most targeting entity for custom double-click action when doing AutoCAD custom programming.

Also, I found my logic in that post may not be good enough. For example, user can click any entity or entities to get it or them highlighted and then double-click anywhere in the Editor to get the code in my Application.BeginDoubleClick event handler run and trigger my custom double-click action, because in this case, Editor.SelectImplied() still can get "pickfirst" selection set. This may not be user wants.

So, in order to find workaround for the Blockreference with attributes not working issue and make the custom double-click action more accurate on what entity user is actually double-clicked, I worked out a solution that does not use Editor.SelectImplied() in Application.BeginDoubleClick event handler to find out exactly what entity is double-clicked and then do things accordingly (e.g. trigger my custom double-click action if needed).

The logic is like this:

In the Application.BeginDoubleClick event handler, I get current mouse location, and then get the cursor (the pickbox)'s size. Then I use the pickbox' information to get 4 points representing the 4 corners of the pickbox of the cursor when double-clicking occurs. Once the 4 points are available, I use Editor.SelectCrossingPolygon() method to find entity or entities being double-clicked.

This approach is obviously more accurately reflect what user exactly double-clicked on. Depending on the pickbox's size (set by system variable "PICKBOX", value from 0 to 20 pixel), none (when ""PICKBOX" is set to 0) or more entities could be double-clicked.

With this logic in mind, I created and Editor extension method to return a PromptSelectionResult object, which takes a Point3d input (the cursor's location where double-click occurs):

    1 public static class EditorSelectionExtension
    2 {
    3     public static PromptSelectionResult  SelectAtPickBox(
    4         this Editor ed, Point3d pickBoxCentre)
    5     {
    6         //Get pick box's size on screen
    7         System.Drawing.Point screenPt = ed.PointToScreen(pickBoxCentre, 1);
    8 
    9         //Get pickbox's size. Note, the number obtained from
   10         //system variable "PICKBOX" is actually the half of
   11         //pickbox's width/height
   12         object pBox = Application.GetSystemVariable("PICKBOX");
   13         int pSize = Convert.ToInt32(pBox);
   14 
   15         //Define a Point3dCollection for CrossingWindow selecting
   16         Point3dCollection points = new Point3dCollection();
   17 
   18         System.Drawing.Point p;
   19         Point3d pt;
   20 
   21         p = new System.Drawing.Point(screenPt.X - pSize, screenPt.Y - pSize);
   22         pt = ed.PointToWorld(p, 1);
   23         points.Add(pt);
   24 
   25         p = new System.Drawing.Point(screenPt.X + pSize, screenPt.Y - pSize);
   26         pt = ed.PointToWorld(p, 1);
   27         points.Add(pt);
   28 
   29         p = new System.Drawing.Point(screenPt.X + pSize, screenPt.Y + pSize);
   30         pt = ed.PointToWorld(p, 1);
   31         points.Add(pt);
   32 
   33         p = new System.Drawing.Point(screenPt.X - pSize, screenPt.Y + pSize);
   34         pt = ed.PointToWorld(p, 1);
   35         points.Add(pt);
   36 
   37         return ed.SelectCrossingPolygon(points);
   38     }
   39 }

With this extension method available, I simply modified the portion of code for getting selected entity or entities in Application_BeginDoubeClick() event handler of my original solution. Now, my solution for custom double-click action work as good as the original one on every entity type, including BlockReference with attributes, of course. Here is the original code in the Application_BeginDoubleClick() event handler:

    1 private static void Application_BeginDoubleClick(
    2     object sender, BeginDoubleClickEventArgs e)
    3 {
    4     _customCmd = null;
    5     _selectedEntId = ObjectId.Null;
    6 
    7     //Get entity which user double-clicked on
    8     Editor ed=Application.DocumentManager.MdiActiveDocument.Editor;
    9     PromptSelectionResult res = ed.SelectImplied();
   10     if (res.Status == PromptStatus.OK)
   11     {
   12         ObjectId[] ids = res.Value.GetObjectIds();
   13 
   14         //Only when there is one entity selected, we go ahead to see
   15         //if there is a custom command supposed to target at this entity
   16         if (ids.Length == 1)
   17         {
   18             //Find mapped custom command name
   19             string cmd = _customCommands.GetCustomCommand(ids[0]);
   20             if (!string.IsNullOrEmpty(cmd))
   21             {
   22                 _selectedEntId = ids[0];
   23                 _customCmd = cmd;
   24 
   25                 ed.WriteMessage("\nRun command {0} agianst entity {1}",
   26                     _customCmd, _selectedEntId.ToString());
   27 
   28                 if (System.Convert.ToInt32(
   29                     Application.GetSystemVariable("DBLCLKEDIT")) == 0)
   30                 {
   31                     //Since "Double click editing" is not enabled, we'll
   32                     //go ahead to launch our custom command
   33                     LaunchCustomCommand(ed);
   34                 }
   35                 else
   36                 {
   37                     //Since "Double Click Editing" is enabled, a command
   38                     //defined in CUI/CUIX will be fired. Let the code return
   39                     //and wait the DocumentLockModeChanged and
   40                     //DocumentLockModeChangeVetoed event handlers do their job
   41                     return;
   42                 }
   43             }
   44             else
   45             {
   46                 ed.WriteMessage(
   47                     "\nNo custom command is defined agaist the selected entity.");
   48             }
   49         }
   50     }
   51     else
   52     {
   53         ed.WriteMessage("\nNo entity or more than 1 entities selected.");
   54     }
   55 }

Here is updated code in the Application_BeginDoubleClick event handler:

    1 private static void Application_BeginDoubleClick(
    2     object sender, BeginDoubleClickEventArgs e)
    3 {
    4     _customCmd = null;
    5     _selectedEntId = ObjectId.Null;
    6 
    7     //Get entity which user double-clicked on
    8     Editor ed=Application.DocumentManager.MdiActiveDocument.Editor;
    9     PromptSelectionResult res = ed.SelectAtPickBox(e.Location);
   10     if (res.Status == PromptStatus.OK)
   11     {
   12         ObjectId[] ids = res.Value.GetObjectIds();
   13 
   14         //Only when there is one entity selected, we go ahead to see
   15         //if there is a custom command supposed to target at this entity
   16         if (ids.Length == 1)
   17         {
   18             //Find mapped custom command name
   19             string cmd = _customCommands.GetCustomCommand(ids[0]);
   20             if (!string.IsNullOrEmpty(cmd))
   21             {
   22                 _selectedEntId = ids[0];
   23                 _customCmd = cmd;
   24 
   25                 ed.WriteMessage("\nRun command {0} agianst entity {1}",
   26                     _customCmd, _selectedEntId.ToString());
   27 
   28                 if (System.Convert.ToInt32(
   29                     Application.GetSystemVariable("DBLCLKEDIT")) == 0)
   30                 {
   31                     //Since "Double click editing" is not enabled, we'll
   32                     //go ahead to launch our custom command
   33                     LaunchCustomCommand(ed);
   34                 }
   35                 else
   36                 {
   37                     //Since "Double Click Editing" is enabled, a command
   38                     //defined in CUI/CUIX will be fired. Let the code return
   39                     //and wait the DocumentLockModeChanged and
   40                     //DocumentLockModeChangeVetoed event handlers do their job
   41                     return;
   42                 }
   43             }
   44             else
   45             {
   46                 ed.WriteMessage(
   47                     "\nNo custom command is defined agaist the selected entity.");
   48             }
   49         }
   50     }
   51     else
   52     {
   53         ed.WriteMessage("\nNo entity or more than 1 entities selected.");
   54     }
   55 }

As you can see, once the extension method Editor.SelectAtPickBox() is available, I only changed one line of the code in the original solution.

Now my custom double-click action by-passes the possible AutoCAD .NET API bug that prevents BlockReference with attribute from being selected by Editor.SelectImplied().

To see the whole solution of custom double-click action, go the link provided at the beginning of the article.

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.