在C#中用COM操作CAD

一、介绍

AutoCAD的二次开发形式非常多, 有Autolisp,ObjectARX,VBA等,在本章我给大家介绍的是不太常用的COM方式操作CAD。

使用COM的方式有前期绑定和后期绑定2种。

二、示例代码

1、前期绑定

 1 namespace ConsoleApplication2
 2 {
 3     class Program
 4     {
 5         static void Main(string[] args)
 6         {
 7             Autodesk.AutoCAD.Interop.AcadApplication app = new Autodesk.AutoCAD.Interop.AcadApplication();
 8             app.Visible = true;
 9             AcadDocument doc = app.ActiveDocument;
10             double []spoint = {0,0,0};
11             double []epoint = { 0, 1000, 0 };
12             doc.ModelSpace.AddLine(spoint,epoint);
13             app.ZoomAll();
14 
15          //添加工具栏
16             AcadToolbar tool = app.MenuGroups.Item(0).Toolbars.Add("test toolbar group");
17             AcadToolbarItem tbaritem = tool.AddToolbarButton(0, "mycommand1","new line","L " ,false);
18             tbaritem.SetBitmaps("Small iconname ", "Big iconname ");
19             Console.ReadLine();
20         }
21     }
22 }

2、后期绑定

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.Runtime.InteropServices;
 5 using Autodesk.AutoCAD.Interop;
 6 
 7 
 8 namespace ConsoleApplication2
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             try
15             {
16                 AcadApplication app = (AcadApplication)Marshal.GetActiveObject("AutoCAD.Application.17");
17                 AcadDocument doc = app.ActiveDocument;
18                 double[] spoint = { 0, 0, 0 };
19                 double[] epoint = { 0, 1000, 0 };
20                 doc.ModelSpace.AddLine(spoint, epoint);
21                 app.ZoomAll();
22                 AcadToolbar tool = app.MenuGroups.Item(0).Toolbars.Add("test");
23                 AcadToolbarItem tbaritem = tool.AddToolbarButton(0, "mycommand1", "new line", "L ", false);
24                 tbaritem.SetBitmaps("Small iconname ", "Big iconname ");
25                 Console.ReadLine();
26             }
27             catch
28             {
29 
30             }
31             
32         }
}

三、总结

在使用前期绑定速度快于后期绑定,但后期绑定的好处是在未知目标机器上CAD的版本情况下可以指定多个不同的版本。

原文地址:https://www.cnblogs.com/jevon1982/p/9532380.html