C#CAD零基礎學習(照着打一遍理解註釋即可)

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

namespace Civil二次開發項目樣板
{
    /// <summary>
    /// 學習第一冊CAD基礎
    /// </summary>
    public class Part1
    {
        /// <summary>
        /// 獲取當前文檔數量
        /// </summary>
        [CommandMethod("GetDocNumber")]
        public void ListDocs()
        {
            DocumentCollection docs = Application.DocumentManager;//獲取當前所有的文檔集合
            Document doc = docs.MdiActiveDocument;//獲取當前的活躍文檔
            Editor ed = doc.Editor;//獲取編譯器
            ed.WriteMessage("\n文檔數量:\t{0}", docs.Count);//輸出文檔集合數量
            ed.WriteMessage("\n活動文檔爲:\t{0}", doc.Name);//輸出活動文檔名稱
            IEnumerator enumerator = docs.GetEnumerator();//獲取枚舉器
            while (enumerator.MoveNext())//遍歷每個文檔
            {
                doc = enumerator.Current as Document;//獲取當前遍歷文檔
                ed.WriteMessage("\n 文檔名稱:\t{0}", doc.Name);//輸出每個文檔名稱
            }
        }

        /// <summary>
        /// 獲取塊表並打印塊表名稱
        /// </summary>
        [CommandMethod("ListEnts")]
        public void ListDocss()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;//獲取活動文檔
            Editor ed = doc.Editor;//獲取編輯器
            Database db = doc.Database;//獲取數據庫
            //Database db = HostApplicationServices.WorkingDatabase;另一種獲取數據庫方式
            ObjectId blockTblId = db.BlockTableId;//獲取數據庫
            using (Transaction tr = db.TransactionManager.StartTransaction())//創建事務
            {
                BlockTable blockTable = blockTblId.GetObject(OpenMode.ForRead) as BlockTable;//塊表
                foreach (ObjectId btrId in blockTable)//遍歷塊表
                {
                    BlockTableRecord blockTableRecord = btrId.GetObject(OpenMode.ForRead) as BlockTableRecord;//獲取塊表記錄
                    ed.WriteMessage("\n塊表記錄:{0}", blockTableRecord.Name);
                    foreach (ObjectId enId in blockTableRecord)//獲取塊表內容中的實體
                    {
                        Autodesk.AutoCAD.DatabaseServices.DBObject obj = enId.GetObject(OpenMode.ForRead);//獲取實體
                        ed.WriteMessage("\n實體模型爲:{0}\t句柄:{1}", obj.GetType().Name, obj.Handle);
                    }
                }
                tr.Commit();//提交事務
            }
        }

        /// <summary>
        /// 通過名稱找到塊表記錄並打印
        /// </summary>
        [CommandMethod("ListBlkRcd")]
        public void ListBlkRcd()
        {
            string[] btrNames = new string[] {
                "*Model_Space","*model_space","*Paper_Space",
                "*Paper_Space0","*Paper_Space1","*Paper_Space2",
                "Line","TestBlock","Something",
                BlockTableRecord.ModelSpace,BlockTableRecord.PaperSpace
            };//塊表記錄的名稱
            Document doc = Application.DocumentManager.MdiActiveDocument;//獲取活動文檔
            Editor ed = doc.Editor;//獲取編輯器
            Database db = doc.Database;//獲取活動文本數據庫
            ObjectId blockTable = db.BlockTableId;//獲取塊表的id
            using (Transaction tr = db.TransactionManager.StartTransaction())//開始數據庫的處理
            {
                BlockTable bt = blockTable.GetObject(OpenMode.ForRead) as BlockTable;//塊表ID轉換爲塊表
                foreach (string btrName in btrNames)//循環塊表名稱
                {
                    if (bt.Has(btrName))//查看塊表中是否有此名稱的塊表記錄的ID  
                    {
                        BlockTableRecord btr = bt[btrName].GetObject(OpenMode.ForRead) as BlockTableRecord;//將塊表記錄的ID轉換爲塊表
                        ed.WriteMessage("\n塊表記錄{0}找到了!\t句柄:{1}", btr.Name, btr.Handle);//控制欄打印
                    }
                    else
                    {
                        ed.WriteMessage("\n塊表記錄{0}不存在!", btrName);//控制欄打印
                    }
                }
            }

        }

        /// <summary>
        /// 讀取字典並打印字典
        /// </summary>
        [CommandMethod("ListNmdDic")]
        public void ListNmdDic()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;//獲取文檔
            Editor ed = doc.Editor;//獲取編輯器
            Database db = doc.Database;//獲取數據庫
            using (Transaction tr=db.TransactionManager.StartTransaction())//開始事務
            {
                DBDictionary nmdDic = db.NamedObjectsDictionaryId.GetObject(OpenMode.ForRead) as DBDictionary;//得到字典
                ed.WriteMessage("\n字典條目數量:{0}",nmdDic.Count);//得到字典中的數量
                string dicName = "ACAD_LAYOUT";//佈局的名稱
                foreach (DBDictionaryEntry dicEntry in nmdDic)//循環字典
                {
                    ed.WriteMessage("\n字典條目名稱:{0}", dicEntry.Key);//打印字典中所有的Key
                    if (dicEntry.Key == dicName)//如果鍵值中有此名稱的Key
                    {
                        DBDictionary layoutDic = nmdDic.GetAt(dicName).GetObject(OpenMode.ForRead) as DBDictionary;//將次鍵值打印並循環
                        ed.WriteMessage("\n字典條目的數量:{0};名稱分別爲:", layoutDic.Count);//打印佈局中的字典數量
                        foreach (DBDictionaryEntry dicEntry1 in layoutDic)
                        {
                            ed.WriteMessage("{0}", dicEntry1.Key);//打印佈局的名稱
                        }
                    }
                }
                tr.Commit();//提交事務
            }
        }
        
        /// <summary>
        /// 通過佈局對象得到佈局塊表記錄
        /// </summary>
        [CommandMethod("ListLayoutDic")]
        public void ListLayoutDic()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;//得到活動文檔
            Editor ed = doc.Editor;//得到編輯器
            Database db = doc.Database;//獲取文檔數據庫
            using (Transaction tr= db.TransactionManager.StartTransaction())//開啓數據庫事務
            {
                DBDictionary dic = db.LayoutDictionaryId.GetObject(OpenMode.ForRead) as DBDictionary;//得到佈局字典
                ed.WriteMessage("\n字典條目數量:{0}", dic.Count);//打印佈局字典的數量
                foreach (DBDictionaryEntry dicEntry in dic)//循環字典佈局
                {
                    Layout layout = dicEntry.Value.GetObject(OpenMode.ForRead) as Layout;//獲取字典的佈局
                    BlockTableRecord btr = layout.BlockTableRecordId.GetObject(OpenMode.ForRead) as BlockTableRecord;//獲取佈局中的塊表記錄
                    ed.WriteMessage("\n{0}對應的塊表記錄{1}", layout.LayoutName, btr.Name); //打印塊表記錄名稱
                }
                tr.Commit();
            }
        }

        //[CommandMethod("向幾何控件中添加點")]
        //public void BlockReferenceToCogoPoint()
        //{
        //    Document doc = Application.DocumentManager.MdiActiveDocument;
        //    CivilDocument civilDoc = CivilApplication.ActiveDocument;
        //    CogoPointCollection cogoPts = civilDoc.CogoPoints;
        //    using (Transaction tr = doc.TransactionManager.StartTransaction())
        //    {
        //        BlockTable blockTable=tr.get
        //    }
        //}

        /// <summary>
        /// 創建泛型類來getobject
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetMyObject<T>(ObjectId id) where T:class
        {
            T myObject = null;//創建泛型類的變量
            Database db = HostApplicationServices.WorkingDatabase;//通過當前應用得到工作中的數據庫
            using (Transaction tr = db.TransactionManager.StartTransaction())//開啓事務
            {
                myObject = tr.GetObject(id, OpenMode.ForRead) as T;//獲取類
                tr.Commit();//提交事務
                //tr.Abort();放棄事務
            }
            return myObject;//返回值
        }
        
        /// <summary>
        /// 處理報錯及報錯原因
        /// </summary>
        [CommandMethod("ExceptionTest1")]
        public void ExceptionTest1()
        {
            CivilDocument civilDoc = CivilApplication.ActiveDocument;//獲取civil的文檔
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;//編輯器
            try
            {
                ObjectId pointStyleId = civilDoc.Styles.SurfaceStyles["某某樣式"];//通過名稱查找樣式
            }
            catch(ArgumentException e)//報錯檢測
            {
                ed.WriteMessage(e.Message);//打印報錯原因
            }
            ed.WriteMessage("\n程序運行結束");
        }

        /// <summary>
        /// 從命令行獲取整數
        /// </summary>
        [CommandMethod("GetInteger")]
        public void IntegerTest()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;//獲取編輯器
            PromptIntegerOptions pio = new PromptIntegerOptions("輸入一個整數");//提示選項
            pio.AllowNegative = false;//不能爲負數
            pio.AllowNone = false;//不能爲空值
            pio.AllowZero = false;//不能爲0
            pio.DefaultValue = 1;//默認初始值
            PromptIntegerResult pir = ed.GetInteger(pio);//從命令行獲取整數並將提示選項加入
            if (pir.Status == PromptStatus.OK)//判斷狀態是否爲OK
            {
                ed.WriteMessage(string.Format("\n您輸入的是{0}", pir.Value));//得到並輸出值
            }
        }
        
        /// <summary>
        /// 輸入實數及關鍵字獲取值
        /// </summary>
        [CommandMethod("GetDouble")]
        public void DoubleTest()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;//獲取編譯器
            PromptDoubleOptions pdo = new PromptDoubleOptions("輸入一個實屬或");//提示選項
            pdo.Keywords.Add("Pi", "Pi", "派<Pi>");//添加特殊值
            pdo.Keywords.Add("Two-Pi", "Two-pi", "二派<Two-pi>");//添加特殊值
            pdo.AllowNone = false;//不可輸入空值
            pdo.AllowZero = false;//不可輸入0
            pdo.DefaultValue = 1.0;//默認值
            PromptDoubleResult pdr = ed.GetDouble(pdo);//從編譯器中獲取值
            if (pdr.Status == PromptStatus.Keyword)//當爲關鍵值的時候
            {
                switch (pdr.StringResult)//進行篩選
                {
                    case "Pi"://等於Pi
                        {
                            ed.WriteMessage("\n輸入的值爲3.14");
                            break;
                        }
                    case "Two-Pi"://等於TWO-pi
                        {
                            ed.WriteMessage("\n輸入的值爲6.28");
                            break;
                        }
                    default:
                        ed.WriteMessage("\n輸入的關鍵字無效");
                        break;
                }
            }
            else if (pdr.Status == PromptStatus.OK)//當值爲正常狀態時
            {
                ed.WriteMessage("\n用戶輸入:" + pdr.Status.ToString());
            }
        }

        /// <summary>
        /// 通過選取兩個點生成一個臨時向量
        /// </summary>
        [CommandMethod("GetPoint")]
        public void PointTest()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;//獲取編輯器
            PromptPointOptions ppo = new PromptPointOptions("拾取線段起點");//創建選擇提示
            PromptPointResult ppr = ed.GetPoint(ppo);//獲取點並將選擇樣式載入
            Point3d start = ppr.Value;//獲取開始點
            if(ppr.Status==PromptStatus.Cancel)//如果escGetOptions
            {
                ed.WriteMessage("\n使用(0,0,0)作爲起點");//默認將初始值0,0,0爲start賦值
            }
            ppo.Message = "\n拾取線段終點";//修改選擇提示文字內容
            ppo.UseBasePoint = true;//選擇擁有基點
            ppo.BasePoint = start;//選擇基點
            ppo.UseDashedLine = true;//選擇是否有虛線
            ppr = ed.GetPoint(ppo);//獲取終點
            Point3d end = ppr.Value;//將終點放入變量end
            if (ppr.Status == PromptStatus.Cancel)//如果被esc
            {
                ed.WriteMessage("\n使用(500,500,500)作爲終點");
                end = new Point3d(50, 50, 0);//設置默認終點爲(50,50,0)
            }
            ed.DrawVector(start, end, 2, false);//創建兩點向量
        }
        
        /// <summary>
        /// 獲取角度
        /// </summary>
        [CommandMethod("GetAngle")]
        public void AngleTest()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;//獲取編輯器
            PromptAngleOptions pao = new PromptAngleOptions("拾取角度");//設置角度選擇提示
            pao.AllowNone = false;//是否爲空
            pao.UseDashedLine = false;//是否使用虛線
            pao.UseAngleBase = false;//是否使用angleBase(此變量在db中)
            PromptDoubleResult startAngle = ed.GetAngle(pao);
            if (startAngle.Status == PromptStatus.OK)
            {
                ed.WriteMessage("\n拾取的角度爲{0}", startAngle.Value);
            }
        }

        /// <summary>
        /// 選擇單個實體對象
        /// </summary>
        [CommandMethod("GetEntity1")]
        public void EntityTest1()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;//獲取文檔
            Editor ed = doc.Editor;//獲取編輯器
            PromptEntityResult per = ed.GetEntity("\n拾取任意實體:");//拾取編輯器
            if (per.Status == PromptStatus.OK)//當運狀態爲成功時
            {
                ObjectId entid = per.ObjectId;//得到ID
                using (Transaction tr = doc.Database.TransactionManager.StartTransaction())//開啓事務
                {
                    Autodesk.AutoCAD.DatabaseServices.Entity entity = (Autodesk.AutoCAD.DatabaseServices.Entity)tr.GetObject(entid, OpenMode.ForRead, true);//獲取實體實例
                    ed.WriteMessage("\n所選對象類型爲" + entity.GetType().FullName);//打印名稱
                    tr.Commit();
                }
            }
        }

        /// <summary>
        /// 選擇特定對象實例
        /// </summary>
        [CommandMethod("Getentity2")]
        public void EntityTest2() 
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;//創建文檔
            Editor ed = doc.Editor;//編輯器
            PromptEntityOptions peo = new PromptEntityOptions("\n拾取路線");//創建選擇實體提示
            peo.SetRejectMessage("\n選擇的對象類型不是路線,請重新選擇");//當選擇錯誤時彈出的對話框
            peo.AddAllowedClass(typeof(Alignment), true);//添加允許的拾取的實體類型
            PromptEntityResult per = ed.GetEntity(peo);//拾取並添加選擇提示
            if (per.Status == PromptStatus.OK)//當狀態爲OK時
            {
                ObjectId entid = per.ObjectId;//得到實體ID
                using (Transaction tr = doc.Database.TransactionManager.StartTransaction())//開啓數據庫事務
                {
                    Autodesk.AutoCAD.DatabaseServices.Entity entity = (Autodesk.AutoCAD.DatabaseServices.Entity)tr.GetObject(entid, OpenMode.ForRead, true);//獲取實體
                    ed.WriteMessage("\n所選對象類型爲" + entity.GetType().FullName);//打印名稱
                    tr.Commit();
                }
            }
        }

        /// <summary>
        /// 選擇圖層爲0的圓
        /// </summary>
        [CommandMethod("GetSelection")]
        public void SelectionTest()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;//選擇文檔
            Editor ed = doc.Editor;//創建編輯器
            TypedValue[] tv = new TypedValue[]//創建TypeValue集合
            {
                new TypedValue((int)DxfCode.Start,"CIRCLE"),//選擇
                new TypedValue((int)DxfCode.LayerName,"0")//選擇圖層名稱爲0
            };
            SelectionFilter sf = new SelectionFilter(tv);//創建選擇過濾器
            PromptSelectionResult per = ed.GetSelection(sf);//選擇模型
            if (per.Status == PromptStatus.OK)//當狀態爲OK時
            { 
                SelectionSet ss = per.Value;//得到選擇集
                ed.WriteMessage("\n所選對象總數爲:{0}", ss.Count);//輸出總數
            }
        }

        /// <summary>
        ///  通過選擇全部的方式來選擇所有的圓
        /// </summary>
        [CommandMethod("MySelectionAll")]
        public void SelectAllTest()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;//獲取文檔
            Editor ed = doc.Editor;//獲取編輯器
            TypedValue[] tv = new TypedValue[]//創建類型值組
            {
                new TypedValue((int)DxfCode.Start,"CIRCLE")
            };
            SelectionFilter sf = new SelectionFilter(tv);//將類型值組放入過濾器中
            PromptSelectionResult per = ed.SelectAll(sf);//將過濾器放入
            if (per.Status == PromptStatus.OK)//當狀態爲OK時
            {
                SelectionSet ss = per.Value;//獲取集合
                ed.WriteMessage("\n所選對象總數爲{0}", ss.Count);//打印數量
                using (Transaction tr = doc.Database.TransactionManager.StartTransaction())//開啓事務
                {
                    foreach (SelectedObject so in ss)//循環集合
                    {
                        Autodesk.AutoCAD.DatabaseServices.Entity ent = so.ObjectId.GetObject(OpenMode.ForWrite) as Autodesk.AutoCAD.DatabaseServices.Entity;//以寫入的方式打開實例對象
                        ent.ColorIndex = 3;//將其顏色索引設置爲3
                    }
                    tr.Commit();//提交事務
                }
            }
        }

        /// <summary>
        /// 通過選擇窗體選擇實例
        /// </summary>
        [CommandMethod("MySelectCw")]
        public void SelectionCrossingTest()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;//獲取文檔
            Editor ed = doc.Editor;//獲取編輯器
            PromptPointOptions ppo = new PromptPointOptions("拾窗口角點");//設置第一個窗口提示
            PromptPointResult ppr = ed.GetPoint(ppo);//獲取第一個窗口輸出結果
            Point3d start = ppr.Value;
            PromptPointOptions pco = new PromptPointOptions("拾窗口另一個角點");//設置第二個窗口提示
            ppr = ed.GetPoint(ppo);
            Point3d end = ppr.Value;///獲取第二個窗口輸出結果
            PromptSelectionResult per = ed.SelectCrossingWindow(start, end);//通過兩個點作爲參數創建windows窗口選擇
            if (per.Status == PromptStatus.OK)//當選擇狀態爲OK時
            {
                SelectionSet ss = per.Value;//獲取選擇集
                using (Transaction tr = doc.Database.TransactionManager.StartTransaction())//開啓事務
                {
                    foreach (SelectedObject so in ss) //循環選擇集
                    {
                        Autodesk.AutoCAD.DatabaseServices.Entity ent = so.ObjectId.GetObject(OpenMode.ForWrite) as Autodesk.AutoCAD.DatabaseServices.Entity;//以寫入方式獲取選擇集
                        ent.ColorIndex = 3;//將顏色索引設置爲3
                    }
                    tr.Commit();//提交事務
                }
            }
        }
    } 
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章