AutoCAD fires event notifications as a result of specific actions and states. These notifications provide crucial information to our custom applications, allowing them to react in real time to changes in your AutoCAD drawing.
This is a simple example that responds to AutoCAD commands being cancelled. The name of the cancelled command is displayed at the command prompt.
First, we add two commands to turn the event handler monitoring on or off for the AutoCAD document
CommandCancelled
event:using System; using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.EditorInput; // This line is not mandatory, but improves loading performances [assembly: CommandClass(typeof(Ch11AcadPlugin.MyCommands))] namespace Ch11AcadPlugin { public class MyCommands { [CommandMethod("EventON")] public void EventON() { Document doc = Application.DocumentManager.MdiActiveDocument; //Add the event handler doc.CommandCancelled += new CommandEventHandler(doc_CommandCancelled); } [CommandMethod("EventOFF")] public void EventOFF() { Document doc = Application.DocumentManager.MdiActiveDocument; //Remove the event handler doc.CommandCancelled -= new CommandEventHandler(doc_CommandCancelled); }
Now we will add the actual event handler functionality. We will use the
WriteMessage()
method to display the cancelled command name:public static void doc_CommandCancelled(object sender, CommandEventArgs e) { Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; ed.WriteMessage(string.Format( "\n{0} command was cancelled by the user.\n", e.GlobalCommandName)); } } }