In this post, I demonstrate a way to run an alternative command in the place of standard command under certain condition(s), using .NET API.
The ApplicationServices.DocumentCollection class exposes 2 events that can be used for this purpose: DocumentLockModeChanged and DocumentLockModeChangeVetoed. That is, whenever a command is issued in AutoCAD, DocumentLockModeChanged event is fired. The DocumentLockModeChanged event handler also allows the command that causes the DocumentLockModeChanged event to be vetoed. Subsequently, if the command being vetoed (more precisely speaking, the DocumentLockModeChange being vetoed), DocumentLockModeChangeVetoed event fires, which provides us an opportunity to do something else by handling this event.
In order to generalize the way to deal with using multiple custom commands that would replace standard commands under different conditions, I define an interface like this:
Following are 2 classes that implement the interface.
Class "AlternativeSaveCommandOption". It vetoes command "SAVE" and "QSAVE" in certain condition, and run a custom command. The condition can be anything as user needs. For example, if a specific title block exists in a drawing (assuming the title block is only inserted when the drafting work has been completed) and/or a particular attribute of the title block has been set, we want the title block to be updated with data from external data source whenever the drawing is saved. Here is the code:
Class "AlternativeRorateLineCommandOption". The condition for it to veto the built-in "ROTATE" command is when "ROTATE" command is issued against a pre-selected LINE entity (i.e. PickFirst mode is enabled). Here is the code:
We can have define as many classes that implement the interface "IAlternativeCommandOption" as we need to target different existing/built-in commands. The implementation of AlternativeCommandApplied() method allows us to set condition(s) so that the method would return true/false as desired.
Here are 2 custom commands that would be used in place when built-in commands being vetoed:
Finally I implement the IExtensionApplication interface to put everything together into work:
Compile the code the load it into AutoCAD. let's try out the ROTATE command against one or more LINE entity or entities. If the ROTATE command is issued with LINE entity or entities being pre-selected, we can see the custom command "RotateLine" runs instead of standard ROTATE command. However, if no LINE entity is pre-selected, ROTATE command proceeds as usual.
Try SAVE/QSAVE command would always trigger custom SAVETB command, because I did not have code to check condition(s) in AlternativeCommandApplied(0 method and it always return "true".
With the code structure showing here, it would be very easy to add more custom commands as conditional alternatives to existing commands: simply create new class that implements IAlternativeCommandOption and corresponding command methods, and then add them into the List