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:
Code Snippet
- namespace RunAlternativeCommand
- {
- public enum CommandComparisonOption
- {
- CommandNameEquals=0,
- CommandNameContains=1,
- }
- public interface IAlternativeCommandOption
- {
- string[] TargetCommand { get; }
- CommandComparisonOption ComparisonOption { get; }
- string AlternativeCommand { get; }
- bool PickFirstRequired { get; }
- bool AlternativeCommandApplied();
- }
- }
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:
Code Snippet
- namespace RunAlternativeCommand
- {
- public class AlternativeSaveCommandOption
- : IAlternativeCommandOption
- {
- private string[] _tagetCommand;
- private string _alternativeCommand;
- public AlternativeSaveCommandOption(string altCmd)
- {
- _tagetCommand = new string[]
- {
- "SAVE", "QSAVE"
- };
- _alternativeCommand = altCmd;
- }
- #region IAlternativeCommandOption Members
- public string[] TargetCommand
- {
- get { return _tagetCommand; }
- }
- public CommandComparisonOption ComparisonOption
- {
- get { return CommandComparisonOption.CommandNameContains; }
- }
- public string AlternativeCommand
- {
- get { return _alternativeCommand; }
- }
- public bool AlternativeCommandApplied()
- {
- //Check the drawing to see if we want to run alternative saving.
- //For example, we can check if a particular title block has been
- //inserted or its particular attribute has been set. If yes,
- //we want to use alternative saving process to
- // 1. update the title block with data from external data source
- // 2. save the drawing.
- return true;
- }
- public bool PickFirstRequired
- {
- get { return true; }
- }
- #endregion
- }
- }
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:
Code Snippet
- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.EditorInput;
- using Autodesk.AutoCAD.DatabaseServices;
- namespace RunAlternativeCommand
- {
- public class AlternativeRotateLineCommandOption
- : IAlternativeCommandOption
- {
- private string[] _tagetCommand;
- private string _alternativeCommand;
- public AlternativeRotateLineCommandOption(string altCmd)
- {
- _tagetCommand = new string[] { "ROTATE" };
- _alternativeCommand = altCmd;
- }
- #region IAlternativeCommandOption Members
- public string[] TargetCommand
- {
- get { return _tagetCommand; }
- }
- public CommandComparisonOption ComparisonOption
- {
- get { return CommandComparisonOption.CommandNameEquals; }
- }
- public string AlternativeCommand
- {
- get { return _alternativeCommand; }
- }
- public bool AlternativeCommandApplied()
- {
- //Since PickFirst is required,
- //test if there is implied SelectionSet
- ObjectIdCollection selectedIds = GetImpliedSelectionSet();
- if (selectedIds.Count > 0)
- {
- foreach (ObjectId id in selectedIds)
- {
- //If the selected entities include LINE
- //then the alternative command applies
- if (id.ObjectClass.DxfName.ToUpper() == "LINE")
- {
- return true;
- }
- }
- }
- return false;
- }
- public bool PickFirstRequired
- {
- get { return true; }
- }
- #endregion
- #region private methods
- private ObjectIdCollection GetImpliedSelectionSet()
- {
- Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
- PromptSelectionResult res = ed.SelectImplied();
- if (res.Status == PromptStatus.OK)
- {
- return new ObjectIdCollection(res.Value.GetObjectIds());
- }
- return new ObjectIdCollection();
- }
- #endregion
- }
- }
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:
Code Snippet
- using System;
- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.DatabaseServices;
- using Autodesk.AutoCAD.Runtime;
- using Autodesk.AutoCAD.EditorInput;
- using Autodesk.AutoCAD.Geometry;
- [assembly: CommandClass(typeof(RunAlternativeCommand.AlternativeCommands))]
- namespace RunAlternativeCommand
- {
- public class AlternativeCommands
- {
- #region RotateLine alternative command
- [CommandMethod("RotateLine",CommandFlags.UsePickSet)]
- public static void MyRotateLineCommand()
- {
- Document dwg = Application.DocumentManager.MdiActiveDocument;
- Editor ed = dwg.Editor;
- PromptSelectionResult res = ed.SelectImplied();
- if (res.Status != PromptStatus.OK) return;
- ObjectId[] ids = res.Value.GetObjectIds();
- using (Transaction tran =
- dwg.Database.TransactionManager.StartTransaction())
- {
- RotateLines(ids, tran);
- tran.Commit();
- }
- }
- private static void RotateLines(ObjectId[] entIds, Transaction tran)
- {
- foreach (ObjectId id in entIds)
- {
- Line line = tran.GetObject(id, OpenMode.ForWrite) as Line;
- if (line != null)
- {
- RotateLine(line);
- }
- }
- }
- private static void RotateLine(Line line)
- {
- //Do whatever we want. For example, we rotate line 90 degree
- //with its start point as rotating base point
- Point3d pt = line.StartPoint;
- Matrix3d mt = Matrix3d.Rotation(Math.PI / 2, Vector3d.ZAxis, pt);
- line.TransformBy(mt);
- }
- #endregion
- #region Save alternative command
- [CommandMethod("SaveTB")]
- public static void DoMySave()
- {
- Document dwg = Application.DocumentManager.MdiActiveDocument;
- Editor ed = dwg.Editor;
- ed.WriteMessage(
- "\nSearching for title block...");
- ed.WriteMessage(
- "\nRetrieving title block information from database...");
- ed.WriteMessage("\nUpdate title block...");
- ed.WriteMessage("\nSaving current drawing...");
- //Finally, save the drawing
- dwg.Database.SaveAs(dwg.Name, DwgVersion.Current);
- ed.WriteMessage("\nDrawing is saved by custom saving process!\n");
- }
- #endregion
- }
- }
Finally I implement the IExtensionApplication interface to put everything together into work:
Code Snippet
- using System.Collections.Generic;
- using Autodesk.AutoCAD.ApplicationServices;
- using Autodesk.AutoCAD.Runtime;
- [assembly: ExtensionApplication(typeof(
- RunAlternativeCommand.AlternativeCommandInitializer))]
- namespace RunAlternativeCommand
- {
- public class AlternativeCommandInitializer :
- IExtensionApplication
- {
- private static DocumentCollection docs;
- private List<IAlternativeCommandOption> _altCmds;
- private bool _runAltCmd = false;
- private string _altCmdName = "";
- private string _dwgName = "";
- public void Initialize()
- {
- //Initialize alternative commands
- InitializeAltCmds();
- //Add event handlers to intercept commands
- //so that particular command can be vetoed
- //and alternative command can be run, instead.
- docs = Application.DocumentManager;
- docs.DocumentLockModeChanged +=
- new DocumentLockModeChangedEventHandler(
- docs_DocumentLockModeChanged);
- docs.DocumentLockModeChangeVetoed +=
- new DocumentLockModeChangeVetoedEventHandler(
- docs_DocumentLockModeChangeVetoed);
- docs.MdiActiveDocument.Editor.WriteMessage(
- "\nAlternative commands loaded\n");
- }
- public void Terminate()
- {
- }
- #region initialize alternative commands
- private void InitializeAltCmds()
- {
- _altCmds = new List<IAlternativeCommandOption>();
- AddAltRotateLineCommand();
- AddAltSaveCommand();
- }
- private void AddAltRotateLineCommand()
- {
- AlternativeRotateLineCommandOption opt =
- new AlternativeRotateLineCommandOption("RotateLine");
- _altCmds.Add(opt);
- }
- private void AddAltSaveCommand()
- {
- AlternativeSaveCommandOption opt =
- new AlternativeSaveCommandOption("SaveTB");
- _altCmds.Add(opt);
- }
- #endregion
- #region Handle DocumentLockModeChanged/DocumentLockModeChangeVetoed
- private void docs_DocumentLockModeChangeVetoed(object sender,
- DocumentLockModeChangeVetoedEventArgs e)
- {
- if (!_runAltCmd || !_dwgName.Equals(
- e.Document.Name,
- System.StringComparison.InvariantCultureIgnoreCase))
- return;
- //run alternative command
- Document doc = Application.DocumentManager.MdiActiveDocument;
- if (!string.IsNullOrEmpty(_altCmdName))
- {
- doc.SendStringToExecute(
- _altCmdName + " ", true, false, true);
- }
- _runAltCmd = false;
- }
- private void docs_DocumentLockModeChanged(object sender,
- DocumentLockModeChangedEventArgs e)
- {
- //Check lock mode first
- if (e.CurrentMode != DocumentLockMode.Write &&
- e.CurrentMode!=DocumentLockMode.ExclusiveWrite) return;
- _runAltCmd = false;
- _dwgName = e.Document.Name;
- //Loop through alternative command options
- //to see if any alternative command is set to
- //replace current command
- foreach (var cmdOpt in _altCmds)
- {
- bool match = false;
- CommandComparisonOption comp = cmdOpt.ComparisonOption;
- foreach (var opt in cmdOpt.TargetCommand)
- {
- switch (comp)
- {
- case CommandComparisonOption.CommandNameContains:
- if (e.GlobalCommandName.ToUpper().
- Contains(opt.ToUpper()) &&
- e.GlobalCommandName.ToUpper()!=
- cmdOpt.AlternativeCommand.ToUpper())
- {
- match = true;
- }
- break;
- default:
- if (e.GlobalCommandName.ToUpper()
- == opt.ToUpper() &&
- e.GlobalCommandName.ToUpper()!=
- cmdOpt.AlternativeCommand.ToUpper())
- {
- match = true;
- }
- break;
- }
- if (match) break;
- }
- //When the current command is a targeted command
- if (match)
- {
- //If the condition is met
- if (cmdOpt.AlternativeCommandApplied())
- {
- //Veto to current command and set
- //the alternative command to be run
- _altCmdName = cmdOpt.AlternativeCommand;
- _runAltCmd = true;
- e.Veto();
- return;
- }
- }
- }
- }
- #endregion
- }
- }
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
No comments:
Post a Comment