This came up during an internal discussion and I thought it worth sharing here. It’s easy enough to use a point monitor in AutoCAD to determine the current cursor location, but how do we make sure it’s in the current User Coordinate System (UCS) and that we adjust for object snapping (osnap)?
To keep the code simple I’ve been a little lazy: I’m just adding an event handler as a lambda, without worrying about removing it. Also, to avoid a crash when you switch to the New Tab page or a new document and back, the code swallows an eNotApplicable exception thrown by Editor.WriteMessage() – something you probably won’t need, as you’re more likely to take the information and show it elsewhere than via AutoCAD’s command-line.
Here’s the C# code implementing a command (CC) that prints the status-bar coordinates to the command-line:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
namespace DisplayCoords
{
public class Commands
{
[CommandMethod("CC")]
public void CursorCoords()
{
var doc = Application.DocumentManager.MdiActiveDocument;
if (doc == null) return;
var ed = doc.Editor;
ed.PointMonitor += (s, e) =>
{
var ed2 = (Editor)s;
if (ed2 == null) return;
// If the call is just to set the last point, ignore
if (e.Context.History == PointHistoryBits.LastPoint)
return;
// Get the inverse of the current UCS matrix, to display in UCS
var ucs = ed2.CurrentUserCoordinateSystem.Inverse();
// Checked whether the point was snapped to
var snapped = (e.Context.History & PointHistoryBits.ObjectSnapped) > 0;
// Transform the snapped or computed point to the current UCS
var pt =
(snapped ?
e.Context.ObjectSnappedPoint :
e.Context.ComputedPoint).TransformBy(ucs);
// Display the point with each ordinate at 4 decimal places
try
{
ed2.WriteMessage("{0}: {1:F4}\n", snapped ? "Snapped" : "Found", pt);
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
if (ex.ErrorStatus != ErrorStatus.NotApplicable)
throw;
}
};
}
}
}
Here’s a video of the post in action:
To really put the code through its paces, I suggest running the CC command and then changing the current UCS to that of an arbitrary 3D view, and then creating some geometry you can snap to. You should see the command-line output remains consistent with the status bar at all times. (Please let me know by posting a comment if that’s not the case.)
That’s almost certainly it for me until January… season’s greetings to those of you who’re still reading this blog. See you back here in 2016!