Author Topic: Command not working in CommandEnded Event  (Read 116 times)

0 Members and 1 Guest are viewing this topic.


  • Mosquito
  • Posts: 6
Command not working in CommandEnded Event
« on: September 20, 2017, 12:06:32 am »
I have a command that calls upon some editor commands to eventually perform an export (to dwf):

Code: [Select]
        public static void X3()
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            var currentFilename = doc.Name;
            var currentPath = Path.GetDirectoryName(currentFilename);
            var drawing = Path.GetFileNameWithoutExtension(currentFilename);
            var fileWithDwfExt = Path.ChangeExtension(drawing, ".dwf");

            var destFile = Path.Combine(currentPath, fileWithDwfExt);

            ed.Command("-xref", "d", "*");
            ed.Command("export", destFile, "a", "y");

This works just fine when executed via the AutoCAD commandline, however when the same routine is called in response to the Command* events:

Code: [Select]
public void Initialize()
            Application.DocumentManager.DocumentCreated += DocumentManager_DocumentCreated;
            foreach (Document doc in Application.DocumentManager)
                doc.CommandEnded += OnCommandEnding;


Code: [Select]
public static void OnCommandEnding(object sender, CommandEventArgs e)

it fails with the following exception:
Code: [Select]
System.Exception {Autodesk.AutoCAD.Runtime.Exception}

as a message.

Anyone know what I'm doing wrong?


  • Water Moccasin
  • Posts: 2089
  • Marseille, France
Re: Command not working in CommandEnded Event
« Reply #1 on: September 20, 2017, 03:54:10 am »

As far as I know, you cannot call a command from an event handler (either using SendStringToExecute, SendCommand or Command).
Speaking English as a French Frog


  • Bull Frog
  • Posts: 402
Re: Command not working in CommandEnded Event
« Reply #2 on: September 27, 2017, 01:23:53 am »
In this sort of situation the Application.Idle event can be your friend to insuring that your code is running from the proper state, just add your callback function to the list then remove it once it's been called.

Code - C#: [Select]
  2.        {
  3.             //code not running in application context
  4.             Autodesk.AutoCAD.ApplicationServices.Application.Idle += Application_Idle;
  5.        }
  7.        static void Application_Idle(object sender, EventArgs e)
  8.        {
  9.            Autodesk.AutoCAD.ApplicationServices.Application.Idle -= Application_Idle;
  10.            //do stuff from application context
  11.        }