AutoCADConnector.cs
using System;
using AutoCAD;
using System.Runtime.InteropServices;
namespace AddMenu
{
public class AutoCADConnector : IDisposable
{
private AcadApplication _application;
private bool _initialized;
private bool _disposed;
public AutoCADConnector()
{
try
{
// Upon creation, attempt to retrieve running instance
_application = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application.16");
}
catch
{
try
{
// Create an instance and set flag to indicate this
_application = new AcadApplicationClass();
_initialized = true;
}
catch
{
Console.Write("请安装AutoCAD");
throw;
}
}
}
// If the user doesn't call Dispose, the
// garbage collector will upon destruction
~AutoCADConnector()
{
Dispose(false);
}
public AcadApplication Application
{
get
{
// Return our internal instance of AutoCAD
return _application;
}
}
// This is the user-callable version of Dispose.
// It calls our internal version and removes the
// object from the garbage collector's queue.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// This version of Dispose gets called by our
// destructor.
protected virtual void Dispose(bool disposing)
{
// If we created our AutoCAD instance, call its
// Quit method to avoid leaking memory.
if (!this._disposed && _initialized)
_application.Quit();
_disposed = true;
}
}
}
//程序代码。
using System;
using System.Collections.Generic;
using System.Text;
using AutoCAD;
namespace AddMenu
{
class Program
{
static void Main(string[] args)
{
using (AutoCADConnector connector = new AutoCADConnector())
{
AcadApplication acadApp = connector.Application;
AcadMenuGroup mnugrpRAA;
mnugrpRAA = acadApp.MenuGroups.Item(0);
// Menu
AcadPopupMenu mnupop;
try
{
mnupop = mnugrpRAA.Menus.Item("文件(&F)");
}
catch
{
mnupop = mnugrpRAA.Menus.Add("文件(&F)");
}
string strCmd;
AcadPopupMenuItem mnupopItem;
strCmd = "start SaveToServer;";// 这个就是你要执行的外部程序.
mnupopItem = mnupop.AddMenuItem(7, "保存到服务器", strCmd);
mnupopItem.TagString = "ID_SavetoServer";
mnugrpRAA.Save(AcMenuFileType.acMenuFileSource);
}
}
}
}