AutoCAD .NET commands are commonly defined in the Modal mode, specified by the CommangFlags.Modal flag. The parameterless signature of the CommandMethod attribute also indicates the CommangFlags.Modal mode by default.
However, in the default and popular Modal command mode, some operations will fail expecially for those document open/close/create related ones.
Here is an example.
[CommandMethod("CloseFails", CommandFlags.Modal)]
public static void CloseFails_Method()
{
Editor ed = MgdAcApplication.DocumentManager.MdiActiveDocument.Editor;
Document doc = MgdAcApplication.DocumentManager.MdiActiveDocument;
try
{
doc.CloseAndDiscard();
}
catch (System.Exception ex)
{
ed.WriteMessage(Environment.NewLine + ex.Message);
}
}
By the way, we explicitly specify the CommandFlags.Modal flag here to make things a bit clearer. If the command is run, an exception saying ‘Drawing is busy’ will occur.
Command: CloseFails
Drawing is busy.
It’s better than crash though, e.g. in the case of creating a new document in the same Modal mode as demonstrated before. It’s an easy problem to solve. Specifying the command with the CommandFlags.Session flag is the way to go!
[CommandMethod("CloseSucceeds", CommandFlags.Session)]
public static void CloseSucceeds_Method()
{
Editor ed = MgdAcApplication.DocumentManager.MdiActiveDocument.Editor;
Document doc = MgdAcApplication.DocumentManager.MdiActiveDocument;
try
{
doc.CloseAndDiscard();
}
catch (System.Exception ex)
{
ed.WriteMessage(Environment.NewLine + ex.Message);
}
}
The leading edge AutoCAD .NET Addin Wizard (AcadNetAddinWizard) always specify the CommandFlags in the commands it defines to make things a bit more transparent even for the default Modal mode. It does not increase typing or clicking at all since all the commands will be created automatically at once and the CommangFlags.Modal flag is defaulted for each command method.
Posted by: |