This very good question came in by email from Patrick Nikoletich:
I was wondering what the preferred method for overriding the default “Open” common dialog in AutoCAD 2007 would be? I can catch the event but can’t send AutoCAD a command to cancel the request so I can launch my Win Form instead.
This is quite a common requirement - especially for people integrating document management systems with AutoCAD.
The simplest way to accomplish this - and this technique goes back a bit - is to undefine the OPEN command, replacing it with your own implementation. The classic way to do this from LISP was to use the (command) function to call the UNDEFINE command on OPEN, and then use (defun) to implement your own (c:open) function.
This technique can be adapted for use with .NET. The following C# code calls the UNDEFINE command in its initialization and then implements an OPEN command of its own.
A few notes on the implementation:
- I'm using the COM SendCommand(), rather than SendStringToExecute(), as it is called synchronously and is executed before the command gets defined
- Unfortunately this causes the UNDEFINE command to be echoed to the command-line, an undesired side effect.
- I have not tested this being loaded on AutoCAD Startup - it may require some work to get the initialization done appropriately, if this is a requirement (as SendCommand is called on the ActiveDocument).
- I've implemented the OPEN command very simply - just to request a filename from the user with a standard dialog - and then call a function to open this file. More work may be needed to tailor this command's behaviour to match AutoCAD's or to match your application requirements.
- This is defined as a session command, allowing it to transfer focus to the newly-opened document. It does not close the active document, which AutoCAD's OPEN command does if the document is "default" and unedited (such as "Drawing1.dwg").
And so here's the code:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Interop;
using System.Runtime.InteropServices;
namespace RedefineOpen
{
public class CommandRedefinitions
: Autodesk.AutoCAD.Runtime.IExtensionApplication
{
public void Initialize()
{
AcadApplication app =
(AcadApplication)Application.AcadApplication;
app.ActiveDocument.SendCommand("_.UNDEFINE _OPEN ");
}
public void Terminate(){}
[CommandMethod("OPEN", CommandFlags.Session)]
static public void Open()
{
DocumentCollection dm = Application.DocumentManager;
Editor ed = dm.MdiActiveDocument.Editor;
PromptOpenFileOptions opts =
new PromptOpenFileOptions(
"Select a drawing file (for a custom command)"
);
opts.Filter = "Drawing (*.dwg)";
PromptFileNameResult pr = ed.GetFileNameForOpen(opts);
if (pr.Status == PromptStatus.OK)
{
dm.Open(pr.StringResult);
}
}
}
}