000

Index Labels

Help AutoCAD Users Visually with Transient Graphics – Part 1

.
An AutoCAD drawing could contains tens or hundreds of thousands entities, which makes it very difficult for a CAD user to find certain entities or specific type of entities he/she is trying to work with. Surely, the CAD user can use “quick select” tool, or other means provided by AutoCAD out of box to find locate what he/she is looking for. However, it would be a nice help if we programmers could make a visual help tool, which would visually prompt the CAD user of the targeting entities when he/she move the mouse around over the entities, or do a window selecting (of many entities). Actually AutoCAD has already provided this kind of capability, such as Quick Properties. But to do this kind of stuff in our own program was not an easy task, or not even possible if you do not do C++, until AutoCAD 2009, in which Transient Graphics API is available for .NET API development.

In this article, I’ll show how to use Transient Graphics to visually “highlight” certain type of entity (lightweight polyline in my code, but you can easily modify the code to target other type of entity): when user moves the cursor over certain type of entity, the entity is highlighted, while the cursor moves away, the highlighting graphics goes away, too.

Here is the code, followed by some explanation:




using System;

using System.Collections.Generic;

using System.Text;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Geometry;

using Autodesk.AutoCAD.GraphicsInterface;



[assembly: CommandClass(typeof(TransientGraphicsSample.TGCommands))]



namespace TransientGraphicsSample

{

public class TGCommands

{

public TGCommands()

{

//

// TODO: Add constructor logic here

//

}



#region Polyline Transient Graphics test



private static PolylineTGTracks mTGTracks = null;

private static IPolylineTGFilter mFilter = null;



[CommandMethod("PolyTGOn")]

public static void TurnOnPolylineTG()

{

if (mTGTracks == null) mTGTracks = new PolylineTGTracks();



//Instantiate polyline filter

if (mFilter == null) mFilter = new MyPolylineTGFilter();



Document dwg =

Application.DocumentManager.MdiActiveDocument;



mTGTracks.

SetMouseOverEntityTransientGraphics

(dwg, mFilter, true);

}



[CommandMethod("PolyTGOff")]

public static void TurnOffPolyTG()

{

if (mTGTracks == null) return;



Document dwg =

Application.DocumentManager.MdiActiveDocument;



mTGTracks.SetMouseOverEntityTransientGraphics

(dwg, null, false);

}



#endregion

}



// A class to hold information of transient graphics created

// in a document

public class TGInformation

{

private Document mDwg;

private Editor mEditor;

private Database mDB;



// Targed entity. Should be a Polyine in this example

private ObjectId mCurrentMouseOverObject = ObjectId.Null;



// A polyline object used as transient graphic object

private Polyline mMouseOverTGObject = null;



// Flaging if the transient graphic visual prompt takes effect

private bool mMouseOverEntityMonitored = false;



// Visual prompt's color

private int mTGColorIndex=1;



// Width of the polyline as transient graphic object

private double mLineWidth = 1.0;



// Targeting polyline filter. See more explanation on

// IPolylineTGFilter interface and its implementation

private IPolylineTGFilter mFilter;



// Constructor

public TGInformation

(

Document dwg,

IPolylineTGFilter filter

)

{

mDwg = dwg;

mEditor = mDwg.Editor;

mDB = mDwg.Database;

mFilter = filter;

}



// Overloaded Constructor

public TGInformation

(

Document dwg,

IPolylineTGFilter filter,

double linewidth

)

{

mDwg = dwg;

mEditor = mDwg.Editor;

mDB = mDwg.Database;

mFilter = filter;

mLineWidth = linewidth;

}



public double TGLineWidth

{

set { mLineWidth = value; }

get { return mLineWidth; }

}



// This property indicates if Mouse-Over

// visual effect is set to on or off

public bool MouseOverEntityMonitored

{

set

{

if (mMouseOverEntityMonitored == value)

{

return;

}



if (value)

{

BeginMonitoringMouseOverEntity();

}

else

{

EndMonitoringMouseOverEntity();

}

}

get

{

return mMouseOverEntityMonitored;

}

}



#region private methods



private void BeginMonitoringMouseOverEntity()

{

//Clear previous transient graphic objec

ClearMouseOverTGObject();



mCurrentMouseOverObject = ObjectId.Null;



//Start handling Editor.PointMinotor event

mEditor.PointMonitor +=

new PointMonitorEventHandler(mEditor_PointMonitor);



mMouseOverEntityMonitored = true;

}



private void EndMonitoringMouseOverEntity()

{

//Remove Ediotr.PointMonitor event handler

mEditor.PointMonitor -=

new PointMonitorEventHandler(mEditor_PointMonitor);



mMouseOverEntityMonitored = false;



//Clear exisitn transient graphic object

ClearMouseOverTGObject();

mCurrentMouseOverObject = ObjectId.Null;

}



// Handling Editor.PointMonitor event. so that

//if the cursor is hovering on targeting polyline,

//transient graphic object is created, thus,

//the targeting polyline is highlighted

void mEditor_PointMonitor(object sender,

PointMonitorEventArgs e)

{

FullSubentityPath[] entPaths =

e.Context.GetPickedEntities();



if (entPaths.Length > 0)

{

//When the cursor does hover something

//Get the ObjectId of the entity

FullSubentityPath entPath = entPaths[0];



ObjectId id = entPath.GetObjectIds()[0];



//If the entity is polyline, in this example

if (id.ObjectClass ==

Polyline.GetClass(typeof(Polyline)))

{

//Add your filter here, to decide if

//this polyline is one of the targeting

//polylines in interest

if (mFilter.IsTGTarget(id))

{

//Set the transient graphic highlight

AddOrModifyMouseOverTGObject(id);

}

}

}

else

{

//No entity present below the cursor,

//so clear transient graphic highlight

ClearMouseOverTGObject();

}

}



//Do the transient graphic highlighting

private void AddOrModifyMouseOverTGObject

(ObjectId id)

{

if (mCurrentMouseOverObject == id)

{

//If the cursor is moving over on the

//same targeting polyline, update the

//highlight (changing its color) to

//achieve eye-catching effect

ModifyMouseOverTG();

}

else

{

//Create a new transient graphic object

mCurrentMouseOverObject = id;

AddMouseOverTGObject();

}

}



// Clear existing transient graphic effect

private void ClearMouseOverTGObject()

{

if (mMouseOverTGObject != null)

{

//Remove transient graphic effect

IntegerCollection intCol =

new IntegerCollection();



TransientManager.CurrentTransientManager.

EraseTransient(mMouseOverTGObject, intCol);



//dispose the polyline used to

//show transient graphic effect

mMouseOverTGObject.Dispose();

mMouseOverTGObject = null;

}

}



//Create new transient graphic object

private void AddMouseOverTGObject()

{

//Get the targeting polyline

Polyline target = GetTargetPolyline();



//Create transient graphic polyline,

//which the exactly the same as

//the targeting polyline geometrically

mMouseOverTGObject =

new Polyline(target.NumberOfVertices);



//Set vertices' coordinate and width

for (int i = 0; i < target.NumberOfVertices; i++)

{

Point2d pt = target.GetPoint2dAt(i);

mMouseOverTGObject.AddVertexAt

(i, pt, 0.0, mLineWidth, mLineWidth);

}



//Set color

mMouseOverTGObject.ColorIndex = mTGColorIndex;



//Let the color changes from 1 to 8

//so that when mouse moves, highlighting

//color changes

mTGColorIndex += 1;

if (mTGColorIndex > 8) mTGColorIndex = 1;


mMouseOverTGObject.Closed = target.Closed;

mMouseOverTGObject.SetDatabaseDefaults();



//Add transient graphics

IntegerCollection col = new IntegerCollection();



TransientManager.CurrentTransientManager.

AddTransient

(

mMouseOverTGObject,

TransientDrawingMode.DirectShortTerm,

128,

col

);

}



private void ModifyMouseOverTG()

{

if (mMouseOverTGObject==null)

{

AddMouseOverTGObject();

}

else

{

Polyline target = GetTargetPolyline();



//reset vertices' coordinate, in case the user

//changed the targeting polyline by dragging

//its grip

for (int i = 0;

i < target.NumberOfVertices - 1; i++)

{

Point2d pt = target.GetPoint2dAt(i);

mMouseOverTGObject.SetPointAt(i, pt);

}



//Set color

mMouseOverTGObject.ColorIndex =

mTGColorIndex;



mTGColorIndex += 1;

if (mTGColorIndex > 8) mTGColorIndex = 1;




//Update transient graphics

IntegerCollection col =

new IntegerCollection();



TransientManager.CurrentTransientManager.

UpdateTransient(mMouseOverTGObject, col);

}

}



private Polyline GetTargetPolyline()

{

Polyline target=null;



using (Transaction tran =

mDB.TransactionManager.

StartOpenCloseTransaction())

{

target = tran.GetObject(

mCurrentMouseOverObject,

OpenMode.ForRead) as Polyline;

}



return target;

}



#endregion

}



// A Dictionary collection to hold transient graphics

// information for each opened document

public class PolylineTGTracks :

Dictionary

{

#region public methods



public void SetMouseOverEntityTransientGraphics

(

Document dwg,

IPolylineTGFilter filter,

bool turnOn

)

{

if (turnOn)

{

if (!this.ContainsKey(dwg))

{

TGInformation tgInfo =

new TGInformation(dwg,filter);



this.Add(dwg, tgInfo);

}



//Start monitor mouse moving and

//do the transient graphic highlight

//when targeted polyline is under

//under the mouse cursor

this[dwg].MouseOverEntityMonitored = true;

}

else

{

if (this.ContainsKey(dwg))

{

//Stop transient graphic effect

this[dwg].MouseOverEntityMonitored = false;

}

}

}



//overload, taking a parameter for

//specifc line width

public void SetMouseOverEntityTransientGraphics

(Document dwg, IPolylineTGFilter filter,

double linewidth, bool turnOn)

{

if (turnOn)

{

if (!this.ContainsKey(dwg))

{



TGInformation tgInfo =

new TGInformation(

dwg, filter,linewidth);



this.Add(dwg, tgInfo);

}

else

{

this[dwg].TGLineWidth = linewidth;

}



this[dwg].MouseOverEntityMonitored = true;

}

else

{

if (this.ContainsKey(dwg))

{



this[dwg].MouseOverEntityMonitored



= false;



}

}

}



#endregion

}



// Interface used as filter to find targeting polyline.

// Implement this interface based on your need.

// For example, you can decide if a polyline is the

// targeting entity based on its layer, layout, XData...

public interface IPolylineTGFilter

{

bool IsTGTarget(ObjectId id);

}



//My implementation of IPolylineTGFilter in

//this example: all polylines are targeted

public class MyPolylineTGFilter : IPolylineTGFilter

{



#region PolylineTGFilter Members



public bool IsTGTarget(ObjectId id)

{

//I could do this



//====================



//Entity ent=GetEntityByObjectId(id);



//if ent.Layer!="Layer1") return false;



//=====================



return true;

}



#endregion

}

}



OK, the abundant comments between code lines should be explanative enough, let take look the result of running this code.

To run the code, start AutoCAD (2009/2010), “Netload” the code, draw a couple of polylines, then enter command “PolyTGOn”. Now make cursor move over/out one of the polylines. You would see a very eye-catching highlight appear along the polyline, when the cursor hangs over the target polyline and dispears when the cursor moves out the polyline. See a short video clip here fore the result

You would also notice the highlighting color changes with the move of the cursor, which makes a strong visual prompt, doesn’t it?

Now, open another new drawing and draw a few polylines. However, if you move the mouse cursor over on those polylines, no visual highlighting shows, until you issue command “PolyTGOn” to this drawing.

Of course, if you now switch back to previous drawing, the transient graphic effect is still there until you issue command “PolyTGOff”.

An obviously possible enhancement to this code would be to allow user to configure MyPolylineTGFilter class, so that the transient graphic effect can appear on desired entities according to user inputs.

Blog Archive

Labels

.NET Programming 2D Drafting 3D Animation 3D Artist 3D design 3D Modeling 3D models 3D presentation 3D Printing 3D rendering 3D scanning 3D scene 3D Sketch Inventor 3D visualization 3D Web App 3ds Max 4D Simulation ACC adaptive components Add-in Development Additive Manufacturing Advanced CAD features AEC Technology AEC Tools affordable Autodesk tools AI AI animation AI Assistance AI collaboration AI Design AI Design Tools AI Guide AI in CAD AI in CNC AI in design AI in Manufacturing AI in Revit AI insights AI Tools AI troubleshooting AI-assisted AI-enhanced Animation Animation workflow annotation AR architectural design architectural modeling architectural preservation architectural visualization Architecture architecture design Architecture Engineering Architecture Firm Architecture Productivity architecture software architecture technology Architecture Workflow Arnold Renderer Arnold Shader Artificial Intelligence As-Built Model Asset Management augmented reality AutoCAD AutoCAD advice AutoCAD API AutoCAD Basics AutoCAD Beginner AutoCAD Beginners AutoCAD Civil 3D AutoCAD Civil3D AutoCAD commands AutoCAD efficiency AutoCAD features AutoCAD File Management AutoCAD Layer AutoCAD Layers AutoCAD learning AutoCAD print settings AutoCAD productivity AutoCAD Teaching AutoCAD Techniques AutoCAD tips AutoCAD tools AutoCAD training. AutoCAD tricks AutoCAD Tutorial AutoCAD workflow AutoCAD Xref Autodesk Autodesk 2025 Autodesk 2026 Autodesk 3ds Max Autodesk AI Autodesk AI Tools Autodesk Alias Autodesk AutoCAD Autodesk BIM Autodesk BIM 360 Autodesk Certification Autodesk Civil 3D Autodesk Cloud Autodesk community forums Autodesk Construction Cloud Autodesk Docs Autodesk Dynamo Autodesk features Autodesk for Education Autodesk Forge Autodesk FormIt Autodesk Fusion 360 Autodesk help Autodesk InfraWorks Autodesk Inventor Autodesk Inventor Frame Generator Autodesk Inventor iLogic Autodesk Knowledge Network Autodesk License Autodesk mistakes Autodesk Navisworks Autodesk news Autodesk plugins Autodesk productivity Autodesk Recap Autodesk resources Autodesk Revit Autodesk Software Autodesk support ecosystem Autodesk Takeoff Autodesk Tips Autodesk training Autodesk tutorials Autodesk update Autodesk Upgrade Autodesk Vault Autodesk Video Autodesk Viewer Automated Design Automation Automation Tutorial automotive design automotive visualization Backup Basic Commands Basics Beginner Beginner Tips beginners guide Big Data BIM BIM 360 BIM Challenges BIM collaboration BIM Compliance BIM Coordination BIM Data BIM Efficiency BIM for Infrastructure BIM Implementation BIM Library BIM Management BIM modeling BIM software BIM Standards BIM technology BIM tools BIM Trends BIM workflow Block Editor Building Maintenance building modeling Building Systems Building Technology ByLayer CAD CAD API CAD Automation CAD commands CAD comparison CAD Customization CAD Data Management CAD Design CAD errors CAD Evolution CAD File Size Reduction CAD Integration CAD Learning CAD line thickness CAD management CAD Migration CAD mistakes CAD modeling CAD Optimization CAD plugins CAD Productivity CAD Security CAD Skills CAD software CAD software 2026 CAD software training CAD standards CAD technology CAD Tips CAD Tools CAD Tutorial CAD workflow CAM car design software Case Study CEO Guide CGI design Character Rig Civil 3D Civil 3D hidden gems Civil 3D productivity Civil 3D tips civil design software civil engineering Civil engineering software Clash Detection Class-A surfacing clean CAD file cleaning command client engagement Cloud CAD Cloud Collaboration Cloud design platform Cloud Engineering Cloud Management Cloud Storage Cloud-First CNC CNC machining collaboration command abbreviations Complex Renovation concept car conceptual workflow Connected Design construction Construction Analytics Construction BIM Construction Cloud Construction Planning Construction Scheduling Construction Technology contractor tools Contractor Workflow Contraints corridor design Cost Effective Design cost estimation Create resizable blocks Creative Teams CTB STB Custom visual styles Cybersecurity Data Backup data management Data Protection Data Reference Data Security Data Shortcut Design Automation Design Career Design Collaboration Design Comparison Design Coordination Design Engineering Design Innovation design optimization design productivity design review Design Rules design software design software tips Design Technology design tips Design Tools Design Workflow design-to-construction Designer Designer Tools Digital Assets Digital Construction Digital Construction Technology Digital Content Digital Design Digital engineering digital fabrication Digital Manufacturing digital marketing digital takeoff Digital Thread Digital Tools Digital Transformation Digital Twin Digital Twins digital workflow dimension Disaster Recovery drafting Drafting Standards Drafting Tips Drawing Automation drawing tips Dref Dynamic Block Dynamic Block AutoCAD Dynamic Blocks Dynamic doors Dynamic windows Dynamo automation early stage design eco design editing commands Emerging Features Energy Analysis energy efficiency Engineering Engineering Automation engineering data Engineering Design Engineering Innovation Engineering Productivity Engineering Skills engineering software Engineering Technology engineering tools Engineering Tools 2025 Engineering Workflow Excel Export Workflow Express Tools External Reference Facial Rigging Facility Management Families Fast Structural Design Field Documentation File Optimization File Recovery Flame Forge Development Forge Viewer FreeCAD Fusion 360 Fusion 360 API Fusion 360 tutorial Future of Design Future Skills Game Development Gamification Generative Design Geospatial Data GIS Global design teams grading optimization green building Green Technology Grips Handoff health check Healthcare Facilities heavy CAD file Heavy CAD Files heritage building conservation hidden commands Hospital Design HVAC Design Tools HVAC Engineering Hydraulic Modeling IK/FK iLogic Import Workflow Industry 4.0 Infrastructure infrastructure design Infrastructure Monitoring Infrastructure Planning Infrastructure Technology InfraWorks innovation Insight intelligent modeling Interactive Design interactive presentation Interior Design Inventor Inventor API Inventor Drawing Template Inventor Frame Generator Inventor Graphics Issues Inventor IDW Inventor Tips Inventor Tutorial IoT ISO 19650 Keyboard Shortcuts Keyframe generation Landscape Design Large Projects Laser Scan Layer Management Layer Organization Learn AutoCAD Legacy CAD Licensing Lighting and shading Lighting Techniques Linked Models Machine Learning in CAD Machine Optimization maintenance command Management Manufacturing Innovation Manufacturing Technology Mapping Technology marketing visuals Maya Mechanical Design Mechanical Engineering Media & Entertainment MEP Modeling Mesh-to-BIM Metal Structure Model Management Model Optimization Modular Housing Motion capture MotionBuilder Multi Office Workflow Multi-User Environment multileader Navisworks Navisworks Best Practices Net Zero Design ObjectARX .NET API Open Source CAD Organization OVERKILL OVERKILL AutoCAD Palette Parametric Components parametric design parametric family Parametric Modeling PDF PDM system Personal Brand PlanGrid Plot Style AutoCAD Plugin Tutorial point cloud Portfolio Post Construction Post-Processing Practice Drawing preconstruction workflow predictive analysis Predictive Maintenance Predictive rigging Prefabrication Presentation-ready visuals Printing Quality Procedural animation Procedural Rig Product Design Product Development product lifecycle product rendering Productivity productivity tools Professional 3D design Professional CAD professional printing Professional Tips project efficiency project management Project Management Tools Project Visualization PTC Creo PURGE PURGE AutoCAD Rail Transit Rapid Prototyping realistic rendering ReCap reduce CAD file size Render Render Passes Render Quality Render Settings Rendering rendering engine Rendering Optimization rendering software Rendering Tips Renewable Energy Renovation Project Renovation Workflow Resizable Block restoration workflow Revit Revit add-ins Revit API Revit automation Revit Best Practices Revit Family Revit integration Revit MEP Revit Performance Revit Phasing Revit Scripting Revit skills Revit Standards Revit Template Revit Tips Revit tutorial Revit Workflow Ribbon Rigging robotics ROI Scale Autodesk screen Secure Collaboration Sensor Data Sheet Metal Design Sheet Metal Tricks shortcut keys Shortcuts Siemens NX Simulation Sketch Sketching Tricks Small Firms Smart Architecture Smart Block Smart Building Design Smart City Smart Factory Smart Infrastructur Software Compliance software ecosystem Software Management Software Trends software troubleshooting Software Update Solar Energy Solar Panels SolidWorks Startup Design Steel Structure Design Structural Optimization subscription model Subscription Value sustainability sustainable design Sustainable Manufacturing system performance team training guide Technical Drawing technical support text style Time Management time saving tools toolbar Toolpaths Topography Troubleshooting Tutorial Tutorials urban planning User Interface (UI) Vault Best Practices Vault Lifecycle Vault Mistakes vehicle modeling VFX Viewport configuration Virtual Environments virtual reality visualization workflow VR VR Tools VRED Water Infrastructure Water Management Weight Painting What’s New in Autodesk Wind Energy Wind Turbines Workbook workflow Workflow Automation workflow efficiency Workflow Optimization Workflow Tips Worksets Worksharing Workspace XLS Xref