C# CAD二次开发入门(VS2005+CAD2008)

C#做二次开发显然比C++简单得多。希望公司将来能由C++转向C#

步骤一:
新建C#类库项目HelloArx

找到CAD2008的安装目录,添加acdbmgd.dllacmgd.dll的引用

修改Class1.cs如下:
大气象
using System;
using System.Collections.Generic;
using System.Text;

using Autodesk.AutoCAD;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Colors;
using DBTransMan = Autodesk.AutoCAD.DatabaseServices.TransactionManager;

namespace HelloArx
{
    
public class Class1
    {
        
//加载实体到数据库
        public static ObjectId AppendEntity(Entity ent)
        {
            Database db 
= HostApplicationServices.WorkingDatabase;
            ObjectId entId;
            
using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt 
= (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr 
= (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                entId 
= btr.AppendEntity(ent);
                trans.AddNewlyCreatedDBObject(ent, 
true);
                trans.Commit();

            }
            
return entId;
        }
        
//由两点创建直线
        public static ObjectId AddLine(Point3d startPt, Point3d endPt)
        {

            Line ent 
= new Line(startPt, endPt);
            ObjectId entId 
= AppendEntity(ent);
            
return entId;
        }
    }
}

 

步骤三:

新建一个类NewCmd用来建立Cad命令

大气象
using System;
using System.Collections.Generic;
using System.Text;

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.EditorInput;
using System.Collections;
using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;

[assembly: CommandClass(
typeof(HelloArx.NewCmd))]

namespace HelloArx
{
    
class NewCmd
    {
        
//新建一个命令
        [CommandMethod("test")]
        
public void Test()
        {
            Point3d ptSt 
= new Point3d(000);
            Point3d ptEnd 
= new Point3d(102054);
            Class1.AddLine(ptSt, ptEnd);
        }
    }
}

 

 

步骤四:

右击项目->属性->调试->启动外部程序输入cad的路径
比如F:\Program Files\AutoCAD 2008\acad.exe


Shift+Ctrl+B编译之后。生成HelloArx.dll

 

打开Cad2008输入命令netload找到HelloArx.dll然后输入命令test

可以看到效果。

 

如果看不到,就输入zoom e查看

本文源码:https://files.cnblogs.com/greatverve/csharp-cad.rar

posted @ 2011-02-18 15:38  大气象  阅读(24713)  评论(36编辑  收藏  举报
http://www.tianqiweiqi.com