CSharp啟動(dòng)AutoCAD
一 我們可以通過(guò)AutoCAD安裝以后提供的COM接口啟動(dòng)AutoCAD。
COM組件為:
AutoCAD/ObjectDBX Common 17.1 Type Library (Autodesk.AutoCAD.Interop.Common.dll).
AutoCAD 2009 Type Library (Autodesk.AutoCAD.Interop.dll)
二 方法一
public static void Way1()
{
const string progID = "AutoCAD.Application.17.1";
AcadApplication acApp = null;
try
{
acApp = (AcadApplication)Marshal.GetActiveObject(progID);
}
catch
{
try
{
Type acType = Type.GetTypeFromProgID(progID);
acApp = (AcadApplication)Activator.CreateInstance(acType,true);
}
catch
{
MessageBox.Show("Cannot create object of type \"" +progID + "\"");
}
}
if (acApp != null)
{
// By the time this is reached AutoCAD is fully
// functional and can be interacted with through code
acApp.Visible = true;
acApp.ActiveDocument.SendCommand("_MYCOMMAND ");
}
}三 方法二
public static void Way2()
{
const string progID = "AutoCAD.Application.17.1";
const string exePath = @"E:\Program Files\Autodesk\ACADM 2009\acad.exe";
AcadApplication acApp = null;
// Let's first check we don't have AutoCAD already running
try
{
acApp =(AcadApplication)Marshal.GetActiveObject(progID);
}
catch
{ }
if (acApp != null)
{
MessageBox.Show("An instance of AutoCAD is already running.");
}
else
{
try
{
// Use classes from the System.Diagnostics namespace
// to launch our AutoCAD process with command-line
// options
ProcessStartInfo psi = new ProcessStartInfo(exePath, "/p myprofile");
psi.WorkingDirectory = @"c:\temp";
Process pr = Process.Start(psi);
// Wait for AutoCAD to be ready for input
// This doesn't wait until AutoCAD is ready
// to receive COM requests, it seems
pr.WaitForInputIdle();
// Connect to our process using COM
// We're going to loop infinitely until we get the
// AutoCAD object.
// A little risky, unless we implement a timeout
// mechanism or let the user cancel
while (acApp == null)
{
try
{
acApp = (AcadApplication)Marshal.GetActiveObject(progID);
}
catch
{
// Let's let the application check its message
// loop, in case the user has exited or cancelled
Application.DoEvents();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Cannot create or attach to AutoCAD object: "+ ex.Message);
}
}
if (acApp != null)
{
acApp.Visible = true;
acApp.ActiveDocument.SendCommand("_MYCOMMAND ");
}
}四 當(dāng)然也可以使用C++去調(diào)用COM接口。
posted on 2008-06-17 08:46 夢(mèng)在天涯 閱讀(5509) 評(píng)論(0) 編輯 收藏 引用 所屬分類(lèi): ARX/DBX

