张德长

导航

CAD二次开发 学习笔记(1)

CAD二次开发 学习笔记(1)

 

总结一张关系图

合并两个选择集,并改变所有对象的颜色

        /// <summary>
        /// 合并两次选择的选择集,并将所有选择对象改变颜色
        /// </summary>
        [CommandMethod("MergeSelectionSet")]
        public void MergeSelectionSet()
        {
            //获取编辑器
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //开始选择
            PromptSelectionResult result = ed.GetSelection();
            //声明选择集
            SelectionSet ss = null;
            //声明对象集合
            ObjectIdCollection collection = new ObjectIdCollection();

            //第一次选择
            if (result.Status == PromptStatus.OK)
            {
                ss = result.Value;
                collection = new ObjectIdCollection(ss.GetObjectIds());
                ed.WriteMessage($"第一次选择了{ss.Count}个对象");
            }
            else
            {
                ed.WriteMessage($"第一次选择了{0}个对象");
            }

            //第二次选择
            result = ed.GetSelection();
            if (result.Status == PromptStatus.OK)
            {
                ss = result.Value;
                ed.WriteMessage($"第二次选择了{ss.Count}个对象");
            }
            else
            {
                ed.WriteMessage($"第二次选择了{0}个对象");
            }

            //合并选择集
            if (collection.Count == 0)
            {
                collection = new ObjectIdCollection(ss.GetObjectIds());
            }
            else
            {
                foreach (SelectedObject item in ss)
                {
                    collection.Add(item.ObjectId);
                }
            }

            ed.WriteMessage($"\n一共选择了{collection.Count}个对象");
            //获取数据库
            Database db = HostApplicationServices.WorkingDatabase;
            //改变所有选择对象的颜色
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId item in collection)
                {
                    Entity entity = tr.GetObject(item, OpenMode.ForWrite) as Entity;
                    entity.ColorIndex = 3;
                }
                tr.Commit();
            }
        }

运行结果

通过交叉矩形选择对象

       /// <summary>
        /// 通过交叉窗口进行选择(窗口内的、与窗口相交的都将纳入选择)
        /// </summary>
        [CommandMethod("selectByCrossingWindow")]
        public void SelectByCrossingWindow()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            PromptSelectionResult result = ed.SelectCrossingWindow(new Point3d(2,2,0),new Point3d(10,8,0));
            if (result.Status == PromptStatus.OK)
            {
                SelectionSet ss = result.Value;
                ed.WriteMessage($"选择了{ss.Count}个对象");
            }
            else
            {
                ed.WriteMessage($"选择了{0}个对象");
            }
        }

运行结果

选择并改变颜色(绿色代码3)

       /// <summary>
        /// 选择并将选择对象变成绿色
        /// </summary>
        [CommandMethod("changeColor")]
        public void SelectAndChangeColor()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction tr=db.TransactionManager.StartTransaction())
            {
                PromptSelectionResult result = ed.GetSelection();
                
                if (result.Status==PromptStatus.OK)
                {
                    SelectionSet ss = result.Value;
                    ed.WriteMessage($"选择了{ss.Count}个对象");
                    foreach (SelectedObject selectedObject in ss)
                    {
                        if (selectedObject != null)
                        {
                            Entity entity = tr.GetObject(selectedObject.ObjectId, OpenMode.ForWrite) as Entity;
                            if (entity!=null)
                            {
                                entity.ColorIndex = 3;
                            }
                        }
                    }
                }
                else
                {
                    ed.WriteMessage($"选择了{0}个对象");
                }
                tr.Commit();
            }
        }

运行结果

选择对象Pickfirst

        [CommandMethod("PickFirstSelection",CommandFlags.UsePickSet)]
        public void PickFirstSlection()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;


            PromptSelectionResult result = ed.SelectImplied();
            SelectionSet ss;
            //如果状态OK,说明启动命令前,就已经选择了对象
            if (result.Status==PromptStatus.OK)
            {
                ss = result.Value;
                Application.ShowAlertDialog($"选择了{ss.Count}个对象");
            }
            else
            {
                Application.ShowAlertDialog("选择了0个对象");
            }
            //清空选择集
            ObjectId[] objects = new ObjectId[0];
            ed.SetImpliedSelection(objects);

            result = ed.GetSelection();
            //如果状态OK,说明选择了对象
            if (result.Status == PromptStatus.OK)
            {
                ss = result.Value;
                Application.ShowAlertDialog($"选择了{ss.Count}个对象");
            }
            else
            {
                Application.ShowAlertDialog("选择了0个对象");
            }

        }

运行结果

添加图案填充升级版Hatch

       /// <summary>
        /// 添加图案填充【升级版】
        /// </summary>
        /// 
        int hatchY = 0;
        [CommandMethod("hatchCmdPlus")]
        public void HatchCmdPlus()
        {
            Database db = HostApplicationServices.WorkingDatabase;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                Random random = new Random();
                List<string> hatchTypeList = new List<string>() { "ANSI31", "SOLID", "ANGLE", "BRSTONE", "CLAY", "PLASTI", "MUDST", "SWAMP" };
                for (int i = 0; i < 20; i++)
                {
                    Circle circle = new Circle(new Point3d(random.Next(0, 300), random.Next(0+ hatchY, 200+ hatchY), 0), Vector3d.ZAxis, random.Next(10, 30));
                    btr.AppendEntity(circle);
                    tr.AddNewlyCreatedDBObject(circle, true);
                    //添加到对象集合
                    ObjectIdCollection collection = new ObjectIdCollection();
                    collection.Add(circle.ObjectId);
                    //先添加
                    Hatch hatch = new Hatch();
                    btr.AppendEntity(hatch);
                    tr.AddNewlyCreatedDBObject(hatch, true);

                    //再设置,关联Associative要在AppendLoop之前设置
                    hatch.SetHatchPattern(HatchPatternType.PreDefined, hatchTypeList[random.Next(0,hatchTypeList.Count)]);
                    hatch.Associative = true;
                    hatch.Color = Color.FromColorIndex(ColorMethod.ByAci,(short)random.Next(0,100));
                    hatch.AppendLoop(HatchLoopTypes.Outermost, collection);
                    hatch.EvaluateHatch(true);
                }
                tr.Commit();
            }
            hatchY += 300;
            //总结:Hatch创建需要严格遵循顺序操作
            //0、准备工作:创建填充对象并添加到对象集合ObjectIdCollection
            //1、创建hatch,
            //2、添加hatch到块表记录和事务,
            //3、设置hatch
            //3.1、设置填充模式SetHatchPattern
            //3.2、设置关联Associative
            //3.3、设置循环模式AppendLoop
            //3.4、进行计算EvaluateHatch
            //要点:先添加,再设置;先关联,再循环;
        }

运行结果

添加图案填充Hatch

            //总结:Hatch创建需要严格遵循顺序操作
            //0、准备工作:创建填充对象并添加到对象集合ObjectIdCollection
            //1、创建hatch,
            //2、添加hatch到块表记录和事务,
            //3、设置hatch
            //3.1、设置填充模式SetHatchPattern
            //3.2、设置关联Associative
            //3.3、设置循环模式AppendLoop
            //3.4、进行计算EvaluateHatch
            //要点:先添加,再设置;先关联,再循环;

        /// <summary>
        /// 添加图案填充
        /// </summary>
        [CommandMethod("hatchCmd")]
        public void HatchCmd()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            
            using (Transaction tr=db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                Circle circle = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, 10);
                btr.AppendEntity(circle);
                tr.AddNewlyCreatedDBObject(circle,true);

                //添加到对象集合
                ObjectIdCollection collection = new ObjectIdCollection();
                collection.Add(circle.ObjectId);
                //先添加
                Hatch hatch = new Hatch();
                btr.AppendEntity(hatch);
                tr.AddNewlyCreatedDBObject(hatch, true);
                //再设置,关联Associative要在AppendLoop之前设置
                hatch.SetHatchPattern(HatchPatternType.PreDefined, "ANSI31");
                hatch.Associative = true;
                hatch.AppendLoop(HatchLoopTypes.Outermost, collection);
                hatch.EvaluateHatch(true);

                
                tr.Commit();
            }
            //总结:Hatch创建需要严格遵循顺序操作
            //0、准备工作:创建填充对象并添加到对象集合ObjectIdCollection
            //1、创建hatch,
            //2、添加hatch到块表记录和事务,
            //3、设置hatch
            //3.1、设置填充模式SetHatchPattern
            //3.2、设置关联Associative
            //3.3、设置循环模式AppendLoop
            //3.4、进行计算EvaluateHatch
            //要点:先添加,再设置;先关联,再循环;
        }

运行结果

添加组合区域/面域Region

交集、并集、差集

       /// <summary>
        /// 添加组合区域Region,并设置颜色,求交集、并集、差集
        /// </summary>
        int regionCount = 0;
        double x1 = 0;
        [CommandMethod("compositeRegionCmd")]
        public void CompositeRegionCmd()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            //创建圆
            Circle circle1 = new Circle(new Point3d(x1+2, 2, 0), Vector3d.ZAxis, 10);
            Circle circle2 = new Circle(new Point3d(x1+5, 5, 0), Vector3d.ZAxis, 10);
            //创建对象集合
            DBObjectCollection collection = new DBObjectCollection();
            collection.Add(circle1);
            collection.Add(circle2);

            DBObjectCollection regionCollection = Region.CreateFromCurves(collection);
            Region region1 = regionCollection[0] as Region;
            region1.Color = Color.FromColorIndex(ColorMethod.ByAci,0);
            Region region2 = regionCollection[1] as Region;
            region1.Color = Color.FromColorIndex(ColorMethod.ByAci, 3);

            switch (regionCount)
            {
                case 0://交集
                    region1.BooleanOperation(BooleanOperationType.BoolIntersect,region2);
                    region2.Dispose();
                    db.AddEntityToModelSpace(region1);
                    break;

                case 1://并集
                    region1.BooleanOperation(BooleanOperationType.BoolUnite, region2);
                    region2.Dispose();
                    db.AddEntityToModelSpace(region1);
                    break;

                case 2://差集
                    region1.BooleanOperation(BooleanOperationType.BoolSubtract, region2);
                    region2.Dispose();
                    db.AddEntityToModelSpace(region1);
                    break;
                case 3:
                    db.AddEntityToModelSpace(region1);
                    db.AddEntityToModelSpace(region2);
                    break;

            }
            regionCount++;
            regionCount %= 4;
            x1 += 30;
        }

运行结果

添加区域/面域Region

       /// <summary>
        /// 添加区域Region,并设置颜色
        /// </summary>
        [CommandMethod("RegionCmd")]
        public void RegionCmd()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            //创建圆
            Circle circle1 = new Circle(new Point3d(2, 2, 0), Vector3d.ZAxis, 10);
            Circle circle2 = new Circle(new Point3d(5, 5, 0), Vector3d.ZAxis, 10);
            //创建对象集合
            DBObjectCollection collection = new DBObjectCollection();
            collection.Add(circle1);
            collection.Add(circle2);

            DBObjectCollection regionCollection = Region.CreateFromCurves(collection);
            short i = 1;
            foreach (var item in regionCollection)
            {
                var region = item as Region;
                region.Color = Color.FromColorIndex(ColorMethod.ByAci, i++);
                db.AddEntityToModelSpace(region);
            }

        }

运行结果

添加点DBPoint升级版

        /// <summary>
        /// 添加点,并设置点样式
        /// </summary>
        int x = 0, y = 20, mode = 0;
        [CommandMethod("PointCmd")]
        public void PointCmd()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                //创建点的实体,注意Point3d并不是Entity的子类,应该添加DBPoint类

                DBPoint dBPoint = new DBPoint(new Point3d(2 * x, y, 0));
                btr.AppendEntity(dBPoint);
                tr.AddNewlyCreatedDBObject(dBPoint, true);
                //设置点的样式
                db.Pdmode = 32 + mode;
                x++;
                mode++;
                mode %= 5;

                //设置点的大小
                db.Pdsize = 1;

                tr.Commit();
            }


        }

运行结果

添加实体填充区Solid

        /// <summary>
        /// 添加实体填充
        /// </summary>
        [CommandMethod("SolidCmd")]
        public void SolidCmd()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr=db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId,OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace],OpenMode.ForWrite) as BlockTableRecord;

                Solid solid1 = new Solid(new Point3d(0,0,0),new Point3d(5,0,0),new Point3d(5,8,0),new Point3d(0,8,0));
                solid1.Color = Color.FromColorIndex(ColorMethod.ByColor,1);
                btr.AppendEntity(solid1);
                tr.AddNewlyCreatedDBObject(solid1,true);

                Solid solid2 = new Solid(new Point3d(10, 0, 0), new Point3d(15, 0, 0), new Point3d(10, 8, 0), new Point3d(15, 8, 0));
                solid2.Color = Color.FromColorIndex(ColorMethod.ByColor, 3);
                btr.AppendEntity(solid2);
                tr.AddNewlyCreatedDBObject(solid2,true);

                tr.Commit();
            }
        }

运行结果

添加点DBPoint

点的样式编码(本例添加代号34样式的点)

int x = 4;
        [CommandMethod("PointCmd")]
        public void PointCmd()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction tr=db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId,OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace],OpenMode.ForWrite) as BlockTableRecord;
                //创建点的实体,注意Point3d并不是Entity的子类,应该添加DBPoint类
                DBPoint dBPoint = new DBPoint(new Point3d(x,3,0));
                btr.AppendEntity(dBPoint);
                tr.AddNewlyCreatedDBObject(dBPoint,true);
                //设置点的样式
                db.Pdmode = 34;
                //设置点的大小
                db.Pdsize = 1;
                x++;
                tr.Commit();
            }

运行结果

用EntityJig动态绘制一条直线

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

[assembly: CommandClass(typeof(JigTest.LineJig))]
namespace JigTest
{
    /// <summary>
    /// 命令类
    /// </summary>
    public class LineJig
    {
        /// <summary>
        /// 命令方法
        /// </summary>
        [CommandMethod("linejig")]
        public void DoIt()
        {
            
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptPointOptions options = new PromptPointOptions("\n 指定起点");
            ed.WriteMessage("\n 准备接收用户输入的点");
            PromptPointResult result = ed.GetPoint(options);//阻塞方法
            ed.WriteMessage("\n 已获取用户输入的点");
            ed.WriteMessage($"\n 起点坐标:{result.Value.X},{result.Value.Y},{result.Value.Z}");
            Database db = Application.DocumentManager.MdiActiveDocument.Database;
            LineJigImpl jig = new LineJigImpl(result.Value);
            
            Application.DocumentManager.MdiActiveDocument.Editor.Drag(jig);
            
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                
                btr.AppendEntity(jig.GetEntity());
                tr.AddNewlyCreatedDBObject(jig.GetEntity(),true);
                tr.Commit();
            }
        }
    }
    /// <summary>
    /// Jig实现类
    /// </summary>
    class LineJigImpl : EntityJig
    {
        Point3d m_StartPoint, m_EndPoint;
        Editor editor = Application.DocumentManager.MdiActiveDocument.Editor;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="start">起点</param>
        public LineJigImpl(Point3d start) : base(new Line())
        {
            editor.WriteMessage("\n 执行构造函数");
            m_StartPoint = start;
            editor.WriteMessage($"\n m_StartPoint初始值:{m_StartPoint}");
            editor.WriteMessage($"\n m_EndPoint默认值:{m_EndPoint}");
        }
        /// <summary>
        /// 动态/即时/实时采样器
        /// </summary>
        /// <param name="prompts">即时提示</param>
        /// <returns></returns>
        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            editor.WriteMessage("\n 执行Sampler;");
            JigPromptPointOptions options = new JigPromptPointOptions("\n 指定终点");
            options.UserInputControls =
                    UserInputControls.Accept3dCoordinates |
                    UserInputControls.NoZeroResponseAccepted |
                    UserInputControls.NoNegativeResponseAccepted;

                PromptPointResult result = prompts.AcquirePoint(options);
                Point3d tempPoint = result.Value;
                if (tempPoint != m_EndPoint) m_EndPoint = tempPoint;
                else return SamplerStatus.NoChange;
                if (result.Status == PromptStatus.Cancel) return SamplerStatus.Cancel;
                else return SamplerStatus.OK;
        }
        /// <summary>
        /// (动态/即时/实时)更新显示/动态显示
        /// </summary>
        /// <returns></returns>
        protected override bool Update()
        {
            editor.WriteMessage("\n 执行Update;");
            try
            {
                ((Line)Entity).StartPoint = m_StartPoint;
                ((Line)Entity).EndPoint = m_EndPoint;
                editor.WriteMessage($"\n m_EndPoint当前值:{m_EndPoint}");
            }
            catch (System.Exception)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取实体,便于外部调用
        /// </summary>
        /// <returns></returns>
        public Entity GetEntity()
        { return Entity; }
    }
}

运行结果

列出实体信息

[CommandMethod("listEntity")]
        public void ListEntity()
        {
            Database db = Application.DocumentManager.MdiActiveDocument.Database;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                ed.WriteMessage($"\ndb.BlockTableId:{db.BlockTableId}");
                ed.WriteMessage($"\nBlockTableRecord.ModelSpace:{BlockTableRecord.ModelSpace}");
                ed.WriteMessage($"\nbt[BlockTableRecord.ModelSpace]:{bt[BlockTableRecord.ModelSpace]}");

                ed.WriteMessage($"\n BlockBeginId:{btr.BlockBeginId}");
                ed.WriteMessage($"\n BlockEndId:{btr.BlockEndId}");
                ed.WriteMessage($"\n btr.Name:{btr.Name}");
                ed.WriteMessage($"\n btr.PathName:{btr.PathName}");
                ed.WriteMessage($"\n btr.Comments:{btr.Comments}");
                ed.WriteMessage($"\n --------------------------------");

                int count = 0;
                foreach (ObjectId entityId in btr)
                {
                    ed.WriteMessage($"\n 这是模型空间的第{count + 1}个实体,详细信息如下:");
                    ed.WriteMessage($"\nName:{entityId.ObjectClass.Name}");
                    ed.WriteMessage($"\nAppName:{entityId.ObjectClass.AppName}");
                    ed.WriteMessage($"\nDxfName:{entityId.ObjectClass.DxfName}");
                    count++;
                }
                ed.WriteMessage($"\n块表-模型空间-实体个数:{count}");
            }
        }

运行结果

 

posted on 2022-04-23 00:59  张德长  阅读(1337)  评论(0编辑  收藏  举报