Also, some AutoCAD built-in commands show dialog boxes other then File Open/Save dialog box. By AutoCAD convention, if we execute these command with prefix "-", the command would execute its command-line version for user inputs, if the command does have a command-line version.
When we do our custom AutoCAD programming, we should try our best to follow these AutoCAD convention to make our custom command script-able, whenever it is possible and/or necessary.
This post discusses making custom command showing/not showing File Open/Save dialog box, according to system variable "FILEDIA" value.
It turned out, it is rather easy, in terms of writing code, as shown below.
[CommandMethod("MyCmd")]
public static void RunMyCommand()
{
var dwg = CadApp.DocumentManager.MdiActiveDocument;
var ed = dwg.Editor;
try
{
var fDia = Convert.ToInt32(CadApp.GetSystemVariable("FILEDIA"));
var fileName = GetFileNameFromEditor(ed, fDia);
if (string.IsNullOrEmpty(fileName))
{
CadApp.ShowAlertDialog("Command is cancelled.");
}
else
{
CadApp.ShowAlertDialog($"Command carries on with drawing:\n\n{fileName}");
// Continue the execution with the valid file name,
// such as read the DWG file into side database
}
}
catch (System.Exception ex)
{
ed.WriteMessage("\nError:\n{0}.", ex.Message);
}
finally
{
Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
}
}
private static string GetFileNameFromEditor(Editor ed, int fileDia)
{
while (true)
{
var opt = new PromptOpenFileOptions("\nOpen a drawing file");
opt.DialogCaption = "Open Drawing";
opt.Filter = "AutoCAD Drawing *.dwg|*.dwg";
if (ed.Document.IsNamedDrawing)
{
opt.InitialDirectory = System.IO.Path.GetDirectoryName(ed.Document.Name);
}
opt.PreferCommandLine = fileDia == 0; var res = ed.GetFileNameForOpen(opt); if (res.Status == PromptStatus.OK) { var valid = true; if (opt.PreferCommandLine) { if (!System.IO.File.Exists(res.StringResult)) { ed.WriteMessage( $"\nFile not found:\n{res.StringResult}!"); valid = false; } } if (valid) { return res.StringResult; } } else { return ""; } } }
As the code shows, simply use Editor.GetFileNameForOpen[Save] in conjunction with PromptOpen[Save]FileOption does the trick: simply setting PreferCommandLine property of the PromptFileOptions class to False/True makes Editor.GetFileNameForOpen[Save]() method to either show File Open/Save dialog box, or ask user to enter file path/name at command line. In my code, if the file path/name is to be entered at command line, the code needs to valid the entered file path/name to make sure the file existence (for opening, of course. If it is for saving, creating necessary folder, prompt saving overwriting is warranted in following code).
See this video clip showing how the code works.
2 comments:
THANKS FOR SHARING SUCH A AMAZING CONTENT
GREAT PIECE OF WORK!!!
REALLY APPRECIATE YOUR WORK!!!
CAD to BIM conversion in USA
Thanks for info
autocad drafting in USA
Post a Comment