.NET
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

CommandEnded Event handling with OVERKILL

12 REPLIES 12
SOLVED
Reply
Message 1 of 13
dynamicscope
4202 Views, 12 Replies

CommandEnded Event handling with OVERKILL

public void A()
{
   Document doc = Application.DocumentManager.MdiActiveDocument;
   doc.SendStringToExecute("-overkill\np\n\n\n", true, false, false);
   doc.CommandEnded += new CommandEventHandler(doc_CommandEnded);
}

public void doc_CommandEnded(object sender, CommandEventArgs e)
{
   Document doc = sender as Document;
   if (!doc.Editor.IsQuiescent) return;

   DoSomeWork();
}

 As you can see above, I am trying to call DoSomeWork() after "-overkill" command finishes.

It looks like "-overkill" command is consits of a number of other commands because CommandEnded event gets triggered many times.

So I had to check if Editor is quiescent.

 

But the problem is CommandEnded event does not get tirggered when Editor.IsQuiescent.

So DoSomeWork() never gets called.

 

I also haved tried EnteringQuiescentState event instead of CommandEnded event, but it did not help.

EnteringQuiescentState event also gets called many times before "-overkill" command ends.

 

How could I solve this problem?

Any idea??

12 REPLIES 12
Message 2 of 13


@dynamicscope wrote:

How could I solve this problem?

Any idea??


How to run AutoCAD interactive commands and run code after command completes

Synchronously Send (and wait for) commands in AutoCAD using C# .NET

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 3 of 13

I'm going to respectfully disagree with Alex's advice to do what that article he referred to shows.  

 

That is the absolutely worse possible way to solve a problem like the one you face.

 

How to best solve it depends on if you are trying to execute the command from a modal command handler or from the Application's execution context. In either case, you can use the Editor's RunCommand() method to execute commands synchronously, so that you can easily have control after they've finished.

 

RunCommand() is undocumented and must be invoked via reflection, but that's not hard to do, and you should be able to rely on it continuing to be there, as along as acedCmd() and acedCommand() continue to exist.

 

See this swamp post for more info on using RunCommand.

 

When you are trying to execute commands from the application context (e.g., from an event handler for a control on a Palette, modeless dialog, or the ribbon), you can define your own modal command that you can start using SendStringToExecute(), and that modal command can then use RunCommand() to execute commands syncronously, and allow you to easily get control after the commands have finished.

 

 

Message 4 of 13

Hi, Tony!


@DiningPhilosopher wrote:

I'm going to respectfully disagree with Alex's advice to do what that article he referred to shows.


Then the correct answer would be to totally rewrite the code -OVERKILL command by means of AutoCAD .NET API Smiley Happy

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 5 of 13

Sadly, this approach still does not wait for the "OVERKILL" to end... =(

Message 6 of 13


@dynamicscope wrote:

Sadly, this approach still does not wait for the "OVERKILL" to end... =(


Which of me and Tony approaches do not work? And what code do you use?

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 7 of 13


@dynamicscope wrote:

Sadly, this approach still does not wait for the "OVERKILL" to end... =(


Not sure what approach you're referring to, but the one that I wrote about works.

 

Here is the LISP (command) function call to run OVERKILL using the current options:

 

(command "._-OVERKILL" "ALL" "" "")

 Doing the same using the Command() extension method:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.ApplicationServices;

namespace Namespace1
{
   public static class SyncOverkillExample
   {
      [CommandMethod( "MYOVERKILL" )]
      public static void MyOverkill()
      {
         Document doc = Application.DocumentManager.MdiActiveDocument;
         doc.Editor.Command( "._-OVERKILL", "_ALL", "", "" );

         doc.Editor.WriteMessage( "\nOverkill finished," );
         doc.Editor.WriteMessage( "\ndoing more stuff now...8-)" );

         // TODO: Here you can do what must be done after
         //       the OVERKILL command is finished.
      }
   }
}

namespace Autodesk.AutoCAD.EditorInput
{
   public static class MyEditorExtensions
   {
      static MethodInfo runCommand = typeof( Editor ).GetMethod(
         "RunCommand", BindingFlags.Instance 
            | BindingFlags.NonPublic | BindingFlags.Public );

      public static PromptStatus Command( this Editor ed, params object[] args )
      {
         if( Application.DocumentManager.IsApplicationContext )
            throw new InvalidOperationException( 
               "Invalid execution context for Command()" );
         if( ed.Document != Application.DocumentManager.MdiActiveDocument )
            throw new InvalidOperationException( "Document is not active" );
         return (PromptStatus) runCommand.Invoke( ed, new object[] { args } );
      }
   }
}

 

 

 

Message 8 of 13

hI


@Alexander.Rivilis wrote:

Hi, Tony!


@DiningPhilosopher wrote:

I'm going to respectfully disagree with Alex's advice to do what that article he referred to shows.


Then the correct answer would be to totally rewrite the code -OVERKILL command by means of AutoCAD .NET API Smiley Happy


Well, I don't know if there's a correct oSmiley Winkr incorrect answer, but the best solution IMO, is the one shown by the above example. 

Message 9 of 13

Hi, Tony!

A small clarification. The first version of AutoCAD in which ._-OVERKILL can be invoke with (command ...) is AutoCAD 2012. Previous versions of AutoCAD has lisp-defined command -OVERKILL and can not been called with (command ...) Only with COM-method SendCommand or .NET method SendStringToExecute.

AutoCAD 2011:

Command: (command "._-OVERKILL" "ALL" "" "") ._-OVERKILL Unknown command 
"-OVERKILL".  Press F1 for help.
Command: ALL Unknown command "ALL".  Press F1 for help.

Command: ._-OVERKILL
Initializing...
Select objects: _ALL
0 found
Select objects:

 

 

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 10 of 13

Hi Alex, and thanks.

 

I didn't notice the OP mention what release(s) he needs to work with.

Message 11 of 13

HI, Alex.

 

I have tried one that you suggested with the following code.

 

private void SelectEntitiesOnLayer(Document doc, string layerName)
{
    Editor ed = doc.Editor;

    // Build a filter list so that only entities
    // on the specified layer are selected
    //TypedValue[] tvs = new TypedValue[1] { new TypedValue((int)DxfCode.LayerName, layerName) };
    TypedValue[] tvs = new TypedValue[2] { new TypedValue((int)DxfCode.LayerName, layerName), new TypedValue((int)DxfCode.LayoutName, "Model") };
    SelectionFilter sf = new SelectionFilter(tvs);
    PromptSelectionResult psr = ed.SelectAll(sf);
}

[CommandMethod("MyOverkill")]
public void MyOverkill()
{
    Document doc = Application.DocumentManager.MdiActiveDocument;
    SelectEntitiesOnLayer(doc, LayerName.TIN);
    doc.SendStringToExecute("-overkill\np\n\n\n", true, false, false);
}

[CommandMethod("MoreWork")]
public void MoreWork()
{
    DoSomeWork();
}

[CommandMethod("Test")]
public void Test()
{
    Document doc = Application.DocumentManager.MdiActiveDocument;
    string cmd = @"(command ""MyOverkill"")(while(>(getvar ""cmdactive"")0)(command pause))(command ""MoreWork"") ";
    doc.SendStringToExecute(cmd, true, false, true);
}

 

As you can see, I am expecting DoSomeWork() gets called after "MyOverkill"

Let's say DoSomeWork() is nothing more than poping up the alert.

If I call "Test" command the aleart box pops up immediately, then "-overkill" gets called after.

Which is opposite to what I expected.

 

Did I do something wrong? =(

 

Message 12 of 13

What about this code:

[CommandMethod("Test")]
public void Test()
{
    Document doc = Application.DocumentManager.MdiActiveDocument;
    string cmd;
    cmd = "-overkill\n_p\n\n\n"; 
    doc.SendStringToExecute(cmd, true, false, true);
    cmd = "(while(>(getvar \"cmdactive\")0)(command pause))\n";
    doc.SendStringToExecute(cmd, true, false, true);    
    cmd = "MoreWork\n";
    doc.SendStringToExecute(cmd, true, false, true);    
}

 ?

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

Message 13 of 13

Thank you, Alex~!!

 

Super awesome~!

Looks like this code is working~!! 😃

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report

”Boost