引自 cad人生 的經典代碼

引於:https://www.cnblogs.com/cadlife/articles/2668158.html

using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.AutoCAD.EditorInput ;
using Autodesk.AutoCAD.Runtime ;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices ;
namespace CH02
{
    public class Class1
    {
        //--------------------------------------------------------------
        // 功能:獲取用戶輸入
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //   
        //----------------------------------------------------------------
        [CommandMethod("GetData")]
        public void GetData()
        {
            //獲取Editor對象
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            //獲取整型數據
            PromptIntegerOptions intOp = new PromptIntegerOptions("請輸入多邊形的邊數:");
            PromptIntegerResult intRes;
            intRes = ed.GetInteger(intOp);
            //判斷用戶輸入
            if (intRes.Status == PromptStatus.OK)
            {
                int nSides = intRes.Value;
                ed.WriteMessage("多邊形的邊數爲:" + nSides);
            } if (intRes.Status == PromptStatus.Cancel)
            {
                ed.WriteMessage("用戶按了取消ESC鍵/n" );
            }
        }
        //--------------------------------------------------------------
        // 功能:要求用戶輸入點
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //   
        //----------------------------------------------------------------
   [CommandMethod("PickPoint")]
        static public void PickPoint() 
   {
                //獲取Editor對象
               Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
       PromptPointOptions promptPtOp = new PromptPointOptions("選擇一個點:");
                //指定的基點,如果指定了該點,則在選擇的時候繪製一條橡皮線。
                promptPtOp.BasePoint = new Autodesk.AutoCAD.Geometry.Point3d(0, 0, 0);
       PromptPointResult resPt; 
       resPt = ed.GetPoint(promptPtOp); 
       if (resPt.Status == PromptStatus.OK) 
       {
                    ed.WriteMessage("選擇的點爲:" + resPt.Value.ToString());
       } 
            }

            //--------------------------------------------------------------
            // 功能:獲取選擇集
            // 作者: 
            // 日期:2007-7-20
            // 說明:
            //   
            //----------------------------------------------------------------
   [CommandMethod("SelectEnt")]
        static public void SelectEnt() 
   {
                //獲取Editor對象
               Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
               PromptSelectionOptions selectionOp = new PromptSelectionOptions();
               PromptSelectionResult ssRes = ed.GetSelection(selectionOp);
               if (ssRes.Status == PromptStatus.OK)
               {
                   SelectionSet SS = ssRes.Value;
                   int nCount = SS.Count;
                   ed.WriteMessage("選擇了{0}個實體"  , nCount);
               }      
            }
            //--------------------------------------------------------------
            // 功能:獲取選擇集(帶過濾)
            // 作者: 
            // 日期:2007-7-20
            // 說明:
            //   
            //----------------------------------------------------------------
          [CommandMethod("SelectEnt2")]
        static public void SelectEnt2() 
   {
                //獲取Editor對象
               Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
                // 定義選擇集選項
               PromptSelectionOptions selectionOp = new PromptSelectionOptions();
                 //創建選擇集過濾器,只選擇塊對象
                TypedValue[] filList = new TypedValue[1];
                filList[0] = new TypedValue((int)DxfCode.Start, "INSERT");
               SelectionFilter filter = new SelectionFilter(filList);
               PromptSelectionResult ssRes = ed.GetSelection(selectionOp, filter);
               if (ssRes.Status == PromptStatus.OK)
               {
                   SelectionSet SS = ssRes.Value;
                   int nCount = SS.Count;
                   ed.WriteMessage("選擇了{0}個塊"  , nCount);
               }     
            }
       }
 
  }

using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
namespace CH03
{
    public class Class1
    {
        //--------------------------------------------------------------
        // 功能:創建一個新層
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //----------------------------------------------------------------
        [CommandMethod("CreateLayer")]
        public void CreateLayer()
        {
            ObjectId layerId;
            Database db = HostApplicationServices.WorkingDatabase;
            //開始一個事務
            Transaction trans = db.TransactionManager.StartTransaction();
            try
            {
                //首先取得層表
                LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForWrite);
                //檢查MyLayer層是否存在
                if (lt.Has("MyLayer"))
                {
                    layerId = lt["MyLayer"];
                }
                else
                {
                    //如果MyLayer層不存在,就創建它
                    LayerTableRecord ltr = new LayerTableRecord();
                    ltr.Name = "MyLayer"; //設置層的名字
                    layerId = lt.Add(ltr);
                    trans.AddNewlyCreatedDBObject(ltr, true);
                }
                //提交事務
                trans.Commit();
            }
            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
                //放棄事務
                trans.Abort();
            }
            finally
            {
                // 顯式地釋放
                trans.Dispose();
            }
        }
        //--------------------------------------------------------------
        // 功能:創建一個圓
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //----------------------------------------------------------------
        [CommandMethod("CreateCircle")]
        public void  CreateCircle()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            // 使用 "using" ,結束是自動調用事務的 "Dispose" 
            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);
                //創建一個圓並添加到塊表記錄(模型空間)
                Point3d center = new Point3d(10, 10, 0);
                Circle circle = new Circle(center, Vector3d.ZAxis, 10.0);
                circle.ColorIndex = 1;
                btr.AppendEntity(circle);
                trans.AddNewlyCreatedDBObject(circle, true);
                trans.Commit();
            }
        }
        //--------------------------------------------------------------
        // 功能:創建一個塊定義(塊表記錄)
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //   
        //----------------------------------------------------------------
        public ObjectId CreateBlkDef()
        {
            //定義函數的返回值ObjectId
            ObjectId blkObjId = new ObjectId(); 
            Database db = HostApplicationServices.WorkingDatabase;
            // 使用 "using"關鍵字指定事務的邊界
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //獲取塊表
                BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForWrite);
                //通過塊名myBlkName判斷塊表中是否包含塊表記錄
                if ((bt.Has("myBlkName")))
                {
                    blkObjId = bt["myBlkName"];//如果已經存在,通過塊名獲取塊對應的ObjectId
                }
                else
                {
                    //創建一個圓
                    Point3d center = new Point3d(10, 10, 0); 
                    Circle circle = new Circle(center, Vector3d.ZAxis, 2);
                    circle.ColorIndex = 1;      
                    //創建文本Text:
                    MText text = new MText();
                    text.Contents = " ";
                    text.Location = center;
                    text.ColorIndex = 2;
                    //創建新的塊表記錄 myBlkName
                    BlockTableRecord newBtr = new BlockTableRecord();
                    newBtr.Name = "myBlkName";
                    newBtr.Origin = center;
                    //保存塊表記錄到塊表
                    blkObjId = bt.Add(newBtr); // 返回塊對應的ObjectId
                    trans.AddNewlyCreatedDBObject(newBtr, true); //Let the transaction know about any object/entity you add to the database!
                   
                    //保存新創建的實體到塊表記錄
                    newBtr.AppendEntity(circle); 
                    newBtr.AppendEntity(text);
                    // 通知事務新創建了對象
                    trans.AddNewlyCreatedDBObject(circle, true);
                    trans.AddNewlyCreatedDBObject(text, true);
                }
                trans.Commit(); //提交事務
            }
            return blkObjId;
        }

        //--------------------------------------------------------------
        // 功能:創建一個塊引用
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //----------------------------------------------------------------
        [CommandMethod("CreateBlk")]
        public void CreateBlkRef()
        {
            
             
            //獲取塊的插入點
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptPointOptions ptOps = new PromptPointOptions("選擇塊的插入點");
            PromptPointResult ptRes;
            ptRes = ed.GetPoint(ptOps);
            Point3d ptInsert;
            if (ptRes.Status == PromptStatus.OK)
            {
                ptInsert = ptRes.Value ;
            }
            else
            {
                ptInsert = new Point3d(0, 0, 0);
            }
            Database db = HostApplicationServices.WorkingDatabase;
            // 使用 "using"關鍵字指定事務的邊界
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //獲取塊表和模型空間
                BlockTable bt = (BlockTable)(trans.GetObject(db.BlockTableId, OpenMode.ForWrite));
                BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                
                //創建塊引用
                BlockReference blkRef = new BlockReference(ptInsert,CreateBlkDef());// 指定插入點和所引用的塊表記錄
                blkRef.Rotation = 1.57;//指定旋轉角,按弧度
                //保存新創建的塊引用到模型空間    
                btr.AppendEntity(blkRef); 
                trans.AddNewlyCreatedDBObject(blkRef, true);    // 通知事務新創建了對象
                trans.Commit(); //提交事務
            }
  
        }
        //--------------------------------------------------------------
        // 功能:讀取對象的屬性
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //----------------------------------------------------------------
        [CommandMethod("OpenEnt")]
        public void OpenEnt()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptEntityOptions entOps = new PromptEntityOptions("選擇要打開的對象");
            PromptEntityResult entRes;
            entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("選擇對象失敗,退出");
                return;
            }
            ObjectId objId = entRes.ObjectId;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = (Entity)trans.GetObject(objId, OpenMode.ForWrite);
                ent.ColorIndex = 1;
                trans.Commit();
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
namespace CH04
{
    public class Class1
    {
 
        //--------------------------------------------------------------
        // 功能:通過ObjectId打開對象
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //----------------------------------------------------------------
        [CommandMethod("OpenEnt")]
        public void OpenEnt()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("通過ObjectId打開對象\n");
            PromptEntityOptions entOps = new PromptEntityOptions("選擇要打開的對象\n");
            PromptEntityResult entRes;
            entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("選擇對象失敗,退出");
                return;
            }
            ObjectId objId = entRes.ObjectId;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = trans.GetObject(objId, OpenMode.ForWrite) as Entity ;
                ent.ColorIndex = 1;
                trans.Commit();
            }
  
        }
        //--------------------------------------------------------------
        // 功能:類型識別和轉換
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //----------------------------------------------------------------
        [CommandMethod("GetType")]
        public void GetType()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("數據庫對象的類型識別和轉換\n");
            PromptEntityOptions entOps = new PromptEntityOptions("選擇要打開的對象");
            PromptEntityResult entRes;
            entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("選擇對象失敗,退出");
                return;
            }
            ObjectId objId = entRes.ObjectId;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = trans.GetObject(objId, OpenMode.ForWrite) as Entity;
                ed.WriteMessage("ent.GetRXClass().Name :" + ent.GetRXClass().Name + "\n");
                if (ent is Line)
                {
                    Line aLine = ent as Line;
                    aLine.ColorIndex = 1;
                }
                else if (ent.GetType() == typeof(Circle))
                {
                    Circle cir = (Circle)ent;
                    cir.ColorIndex = 2;
                }
                trans.Commit();
            }
        }
        //--------------------------------------------------------------
        // 功能:實體對象的屬性
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //----------------------------------------------------------------
        [CommandMethod("EntPro")]
        public void EntPro()
        {
             
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("實體對象的屬性\n");
            PromptEntityOptions entOps = new PromptEntityOptions("選擇要打開的對象\n");
            PromptEntityResult entRes;
            entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("選擇對象失敗,退出\n");
                return;
            }
            ObjectId objId = entRes.ObjectId;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = trans.GetObject(objId, OpenMode.ForWrite) as Entity;
                ed.WriteMessage("獲取或設置實體的線型\n");
                ed.WriteMessage("實體的原先的線型爲 :" + ent.Linetype + "\n");
                // 獲取線型表記錄
                LinetypeTable lineTypeTbl = trans.GetObject(db.LinetypeTableId, OpenMode.ForRead) as LinetypeTable;
                // 確保DOT線型名已經加載到當前數據庫
                LinetypeTableRecord lineTypeTblRec = trans.GetObject(lineTypeTbl["DOT"], OpenMode.ForRead) as LinetypeTableRecord;
                // 設置實體的線型
                ent.LinetypeId = lineTypeTblRec.ObjectId;
                // 設置實體的線型比例
                ed.WriteMessage("設置實體的線型比例爲2.0\n");
                ent.LinetypeScale = 2.0;
                //設置實體的可見性
                ent.Visible = true;
                 //設置實體所在的層
                ed.WriteMessage("實體的原先所在的層爲 :" + ent.Layer + "\n");
                ent.Layer = "layer0";
                trans.Commit();
            }
        }
    }
}
  


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
namespace CH05
{
    public class Class1
    {
         //--------------------------------------------------------------
        // 功能:添加擴展數據XDATA
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //----------------------------------------------------------------
        [CommandMethod("AddXData")]
        public void AddXData()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("添加擴充數據XDATA\n");
            PromptEntityOptions entOps = new PromptEntityOptions("選擇要打開的對象\n");
            PromptEntityResult entRes;
            entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("選擇對象失敗,退出");
                return;
            }
            ObjectId objId = entRes.ObjectId;
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = trans.GetObject(objId, OpenMode.ForWrite) as Entity ;
                ent.ColorIndex = 1;
                RegAppTable appTbl = trans.GetObject(db.RegAppTableId, OpenMode.ForWrite) as RegAppTable ;
                if (!appTbl.Has("MyAppName"))
                {
                    RegAppTableRecord appTblRcd = new RegAppTableRecord();
                    appTblRcd.Name = "MyAppName";
                    appTbl.Add(appTblRcd);
                    trans.AddNewlyCreatedDBObject(appTblRcd, true);
                }
                ResultBuffer resBuf = new ResultBuffer();//new TypedValue(1001, "MyAppName"), new TypedValue(1000, "開發部門"));
                resBuf.Add(new TypedValue(1001, "MyAppName"));//註冊程序名稱
                resBuf.Add(new TypedValue(1000 , " 張三"));//姓名
                resBuf.Add(new TypedValue(1000 , " 工程部"));//部門
                resBuf.Add(new TypedValue(1040, 2000.0));//薪水
                ent.XData =  resBuf;
                trans.Commit();
            }
 
        }

        //--------------------------------------------------------------
        // 功能:獲取擴展數據XDATA
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //------------------------------------------------------------
        [CommandMethod("GETXDATA")]
        public void GETXDATA()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("獲取擴充數據XDATA\n");
            PromptEntityOptions entOps = new PromptEntityOptions("選擇帶擴展數據的對象");
            PromptEntityResult entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("選擇對象失敗,退出");
                return;
            }
            Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                Entity ent = (Entity)trans.GetObject(entRes.ObjectId, OpenMode.ForRead);
                ResultBuffer resBuf = ent.XData;
                if (resBuf != null)
                {
                    //
                    IEnumerator iter = resBuf.GetEnumerator();
                    while (iter.MoveNext())
                    {
                        TypedValue tmpVal = (TypedValue)iter.Current;
                        ed.WriteMessage(tmpVal.TypeCode.ToString() + ":");
                        ed.WriteMessage(tmpVal.Value.ToString() + "\n");
                    }
                }
            }
        }
        //--------------------------------------------------------------
        // 功能:在命名對象詞典中添加數據
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //------------------------------------------------------------
        [CommandMethod("AddInNOD")]
        public void AddInNOD()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("在命名對象詞典中添加數據\n");
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //獲取命名對象詞典(NOD)
                DBDictionary NOD =trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite) as DBDictionary ;
                // 聲明一個新的詞典
                DBDictionary copyrightDict;
                // 判斷是否存在COPYRIGHT詞典,沒有則創建
                try
                {
                    // 獲取COPYRIGHT詞典
                    copyrightDict = (DBDictionary)trans.GetObject(NOD.GetAt("COPYRIGHT"), OpenMode.ForRead);
                }
                catch
                {
                    //在NOD下創建COPYRIGHT詞典
                    copyrightDict = new DBDictionary();
                    NOD.SetAt("COPYRIGHT", copyrightDict);
                    trans.AddNewlyCreatedDBObject(copyrightDict, true);
                }
                // 在copyrightDict中,獲取或創建 "author" 詞典
                DBDictionary authorDict;
                try
                {
                    authorDict = (DBDictionary)trans.GetObject(copyrightDict.GetAt("Author"), OpenMode.ForWrite);
                }
                catch
                {
                    authorDict = new DBDictionary();
                    //"author" doesn't exist, create one
                    copyrightDict.UpgradeOpen();
                    copyrightDict.SetAt("Author", authorDict);
                    trans.AddNewlyCreatedDBObject(authorDict, true);
                }
                // 通過Xrecord和ResultBuffer添加擴展數據
                Xrecord authorRec;
                try
                {
                    authorRec = (Xrecord)trans.GetObject(authorDict.GetAt("AuthorInfo"), OpenMode.ForWrite);
                }
                catch
                {
                    authorRec = new Xrecord();
                    authorRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, "張三"));
                    authorDict.SetAt("AuthorInfo", authorRec);
                    trans.AddNewlyCreatedDBObject(authorRec, true);
                }
                trans.Commit();
            }
        }
        //--------------------------------------------------------------
        // 功能:獲取命名對象詞典中的數據
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //------------------------------------------------------------
        [CommandMethod("GetInNOD")]
        public void GetInNod()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("獲取命名對象詞典中數據\n");
            Database db = HostApplicationServices.WorkingDatabase;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                // 獲取NOD 
                DBDictionary NOD = (DBDictionary)trans.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead, false);
                // 獲取COPYRIGHT詞典
                DBDictionary copyrightDict = (DBDictionary)trans.GetObject(NOD.GetAt("COPYRIGHT"), OpenMode.ForRead);
                // 獲取Author詞典
                DBDictionary AuthorDict = (DBDictionary)trans.GetObject(copyrightDict.GetAt("Author"), OpenMode.ForRead);
                // 獲取AuthorInfo擴展記錄Xrecord
                Xrecord authorXRec = (Xrecord)trans.GetObject(AuthorDict.GetAt("AuthorInfo"), OpenMode.ForRead);
                ResultBuffer resBuf = authorXRec.Data;
                TypedValue val = resBuf.AsArray()[0];
                ed.WriteMessage("該圖紙由{0}設計\n", val.Value);
            }
        }
        //--------------------------------------------------------------
        // 功能:添加數據到數據庫對象的擴展詞典中
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //------------------------------------------------------------
        [CommandMethod("AddExtDict")]
        public void AddExtDict()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("創建對象擴展詞典\n");
            PromptEntityOptions entOps = new PromptEntityOptions("選擇要添加擴展數據的塊\n");
            PromptEntityResult entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("選擇對象失敗,退出");
                return;
            }
            Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                DBObject obj = trans.GetObject(entRes.ObjectId, OpenMode.ForWrite) as DBObject;
                BlockReference blkRef;
                if (obj is BlockReference)
                {
                    blkRef = obj as BlockReference;
                }
                else
                {
                    return;
                }
                // 創建對象的擴展詞典
                blkRef.CreateExtensionDictionary();
                DBDictionary extensionDict = (DBDictionary)trans.GetObject(blkRef.ExtensionDictionary, OpenMode.ForWrite, false);
               
                // 通過Xrecord準備附加屬性數據
                Xrecord xRec = new Xrecord();
                xRec.Data = new ResultBuffer(
                  new TypedValue((int)DxfCode.Text, "張三"),// 姓名
                  new TypedValue((int)DxfCode.Real, 1200.0),//薪水
                  new TypedValue((int)DxfCode.Text, "技術部"));// 部門         
               // 在擴展詞典中添加擴展記錄
                extensionDict.SetAt("EmployeeInfomation", xRec); 
                trans.AddNewlyCreatedDBObject(xRec, true);
                trans.Commit();
            }
        }

        //--------------------------------------------------------------
        // 功能:獲取數據庫對象的擴展詞典中的數據
        // 作者: 
        // 日期:2007-7-20
        // 說明:
        //
        //------------------------------------------------------------
        [CommandMethod("GetExtDict")]
        public void GetExtDict()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("獲取對象擴展詞典信息\n");
            PromptEntityOptions entOps = new PromptEntityOptions("選擇添加了擴展數據的塊\n");
            PromptEntityResult entRes = ed.GetEntity(entOps);
            if (entRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("選擇對象失敗,退出");
                return;
            }
            Database db = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                DBObject obj = trans.GetObject(entRes.ObjectId, OpenMode.ForWrite) as DBObject;
                BlockReference blkRef;
                if (obj is BlockReference)
                {
                    blkRef = obj as BlockReference;
                }
                else
                {
                    ed.WriteMessage("選擇對象不是塊,退出\n");
                    return;
                }
                // 創建對象的擴展詞典
                DBDictionary extensionDict = (DBDictionary)trans.GetObject(blkRef.ExtensionDictionary, OpenMode.ForWrite, false);
                // 獲取AuthorInfo擴展記錄Xrecord
                Xrecord EmpXRec = (Xrecord)trans.GetObject(extensionDict.GetAt("EmployeeInfomation"), OpenMode.ForRead);
                ResultBuffer resBuf = EmpXRec.Data;
                TypedValue val = resBuf.AsArray()[0];
                ed.WriteMessage("是員工姓名:{0}\n", val.Value);
                val = resBuf.AsArray()[1];
                ed.WriteMessage("該員工的薪水:{0}\n", val.Value);
                val = resBuf.AsArray()[2];
                ed.WriteMessage("該員工屬於:{0}\n", val.Value);
 
                trans.Commit();
            }
        }
    }
}

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