AutoCAD .NET API基础(三) 集合对象

Collection Objects

集合对象

 

A collection is a type of object that contains many instances of similar objects. The following list contains some of the collection objects that are found in the AutoCAD .NET API:

集合是一种包含了许多相似对象实例的对象类型。下面列出了AutoCAD .NET API里定义的部分集合对象:

Block Table Record 块表记录

Contains all entities within a specific block definition. 含指定块定义里的全部实体;

Block Table 块表

Contains all blocks in the drawing. 含图形文件里的全部块;

Named Objects Dictionary 命名字典

Contains all dictionaries in the drawing. 含图形文件里的全部字典;

Dimension Style Table 标注样式表

Contains all dimension styles in the drawing. 含图形文件里的全部标注样式;

Document Collection 文档集合

Contains all open drawings in the current session. 含当前对话任务里的全部打开的图形文件;

File Dependency Collection 文件依赖性集合

Contains all items in the File Dependency List. 含文件依赖性列表里的全部项;

Group Dictionary 组字典

Contains all groups in the drawing. 含图形文件里的全部组;

Hyperlink Collection 超链接集合

Contains all hyperlinks for a given entity. 含给定实体的全部超链接;

Layer Table 图层表

Contains all layers in the drawing. 含图形文件里的全部图层;

Layout Dictionary 布局字典

Contains all layouts in the drawing. 含图形文件里的全部布局;

Linetype Table 线型表

Contains all linetypes in the drawing. 含图形文件里的全部线型;

MenuBar Collection 菜单栏集合

Contains all menus currently displayed in AutoCAD. AutoCAD当前显示的全部菜单项;

MenuGroup Collection 菜单组集合

Contains all customization groups currently loaded in AutoCAD. A customization group represents a loaded CUIx file which can contain menus, toolbars, and ribbon tabs among other elements that define the user interface.

AutoCAD当前加载的全部自定义组。自定义组代表一个加载CUIx文件,该文件可包含菜单、工具条、ribbon选项卡以及定义用户界面的其他元素。

Plot Configuration Dictionary 绘图配置字典

Contains named plot settings in the drawing. 含图形文件里的命名绘图设置;

Registered Application Table 已注册应用程序表

Contains all registered applications in the drawing. 含图形文件里全部已注册应用程序;

Text Style Table 文字样式表

Contains all text styles in the drawing. 含图形文件里的全部文字样式;

UCS Table UCS

Contains all user coordinate systems (UCS's) in the drawing. 含图形文件里的全部用户坐标系;

View Table 视图表

Contains all views in the drawing. 含图形文件里的全部视图;

Viewport Table 视口表

Contains all viewports in the drawing. 含图形文件里的全部视口;

Topics in this section本节主题

·         Access a Collection 访问集合

·         Add a New Member to a Collection Object 向集合对象添加新成员

·         Iterate through a Collection Object 迭代集合对象

·         Erase a Member of a Collection Object 从集合对象删除成员

 

 

 

1Access a Collection访问集合

Most collection and container objects are accessed through the Document or Database objects. The Document and Database objects contain a property to access an object or object id for most of the available Collection objects. For example, the following code defines a variable and retrieves the LayersTable object which represents the collection of Layers in the current drawing:

多数集合对象和容器对象都是通过Document对象或Database对象来访问。Document对象和Database对象一个属性用来访问大多数可用集合对象的对象或对象ID。例如,下面的代码定义了一个变量并检索LayersTable对象,LayersTable对象表示当前图形文件的图层集合:

VB.NET

'' Get the current document and start the Transaction Manager

Dim acCurDb As Database = Application.DocumentManager.MdiActiveDocument.Database

Using acTrans As Transaction = acCurDb.TransactionManager.StartTransaction()

 

    '' This example returns the layer table for the current database

    Dim acLyrTbl As LayerTable

    acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, _

                                 OpenMode.ForRead)

 

    '' Dispose of the transaction

End Using

C#

// Get the current document and start the Transaction Manager

Database acCurDb = Application.DocumentManager.MdiActiveDocument.Database;

using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())

{

    // This example returns the layer table for the current database

    LayerTable acLyrTbl;

    acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,

                                 OpenMode.ForRead) as LayerTable;

 

     // Dispose of the transaction

}

 

VBA/ActiveX Code Reference VBA/ActiveX代码参考)

 

 

Dim layerCollection as AcadLayers

Set layerCollection = ThisDrawing.Layers

 

 

2Add a New Member to a Collection Object向集合对象添加新成员

To add a new member to the collection, use the Add method. For example, the following code creates a new layer and adds it to the Layer table:

向集合对象添加新成员,使用Add方法。例如,下面的代码新建一个图层并将其添加到Layer表:

VB.NET

Imports Autodesk.AutoCAD.Runtime

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.DatabaseServices

 

_

Public Sub AddMyLayer()

  '' Get the current document and database, and start a transaction

  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument

  Dim acCurDb As Database = acDoc.Database

 

  Using acTrans As Transaction = acCurDb.TransactionManager.StartTransaction()

      '' Returns the layer table for the current database

      Dim acLyrTbl As LayerTable

      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, _

                                   OpenMode.ForRead)

 

      '' Check to see if MyLayer exists in the Layer table

      If Not acLyrTbl.Has("MyLayer") Then

          '' Open the Layer Table for write

          acLyrTbl.UpgradeOpen()

 

          '' Create a new layer table record and name the layer "MyLayer"

          Dim acLyrTblRec As LayerTableRecord = New LayerTableRecord

          acLyrTblRec.Name = "MyLayer"

 

          '' Add the new layer table record to the layer table and the transaction

          acLyrTbl.Add(acLyrTblRec)

          acTrans.AddNewlyCreatedDBObject(acLyrTblRec, True)

 

          '' Commit the changes

          acTrans.Commit()

      End If

 

      '' Dispose of the transaction

  End Using

End Sub

C#

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

 

[CommandMethod("AddMyLayer")]

public static void AddMyLayer()

{

  // Get the current document and database, and start a transaction

// 获取当前文档和数据库,并启动事务;

  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  Database acCurDb = acDoc.Database;

 

  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())

  {

      // Returns the layer table for the current database

// 返回当前数据库图层表;

      LayerTable acLyrTbl;

      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,

                                   OpenMode.ForRead) as LayerTable;

 

      // Check to see if MyLayer exists in the Layer table

      // 检查看图层表里是否有要建的图层MyLayer

      if (acLyrTbl.Has("MyLayer") != true)

      {

          // Open the Layer Table for write

// 打开图层表准备写入;

          acLyrTbl.UpgradeOpen();

 

          // Create a new layer table record and name the layer "MyLayer"

          // 新建一条图层表记录并将新建层命名为“MyLayer”;

          LayerTableRecord acLyrTblRec = new LayerTableRecord();

          acLyrTblRec.Name = "MyLayer";

 

          // Add the new layer table record to the layer table and the transaction

          // 添加新的图层表记录到图层表,添加事务;

          acLyrTbl.Add(acLyrTblRec);

          acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);

 

          // Commit the changes提交事务;

          acTrans.Commit();

      }

 

      // Dispose of the transaction处置事务,回收内存;

  }

}

VBA/ActiveX Code Reference

Sub AddMyLayer()

    Dim newLayer as AcadLayer

    Set newLayer = ThisDrawing.Layers.Add("MyLayer")

End Sub

 

 

3Iterate through a Collection Object迭代集合对象

To select a specific member of a Collection object, use the Item or GetAt method. The Item and GetAt methods require a key in the form of a string in which represents the name of the item. With most collections, the Item method is implied, meaning you do not actually need to use method.

选择集合对象的指定成员,用Item方法或GetAt方法。Item方法和GetAt方法需要一个代表项目名称的字符串形式键值。对大多数集合来说,Item方法是隐含的,这意味着我们其实不需要使用该方法。

With some Collection objects, you can also use an index number to specify the location of the item within the collection you want to retrieve. The method you can use varies based on the language you are using as well as if you are working with a symbol table or dictionary.

对有些集合对象来说,我们还可以用一个索引值来指定一个项目在要检索的集合里的位置。我们所用的这些方法,会因我们所用的编程语言的不同以及我们使用符号表还是使用字典,而有不同的格式。

The following statements show how to access the “MyLayer” table record in Layer symbol table.

下列代码显示怎样访问图层符号表里的MyLayer表记录:

VB.NET

acObjId = acLyrTbl.Item("MyLayer")

 

acObjId = acLyrTbl("MyLayer")

C#

acObjId = acLyrTbl["MyLayer"];

 

 

VBA/ActiveX Code Reference

acLayer = ThisDrawing.Layers.Item("MyLayer")

 

acLayer = ThisDrawing.Layers("MyLayer")

Iterate through the LayerTable object 迭代LayerTable对象

The following example iterates through the LayerTable object and displays the names of all its layer table records:

下面的例子迭代LayerTable对象并显示全部图层表记录的名称:

VB.NET

Imports Autodesk.AutoCAD.Runtime

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.DatabaseServices

 

_

Public Sub IterateLayers()

  '' Get the current document and database, and start a transaction

  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument

  Dim acCurDb As Database = acDoc.Database

 

  Using acTrans As Transaction = acCurDb.TransactionManager.StartTransaction()

      '' This example returns the layer table for the current database

      Dim acLyrTbl As LayerTable

      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, _

                                   OpenMode.ForRead)

 

      '' Step through the Layer table and print each layer name

      For Each acObjId As ObjectId In acLyrTbl

          Dim acLyrTblRec As LayerTableRecord

          acLyrTblRec = acTrans.GetObject(acObjId, OpenMode.ForRead)

 

          acDoc.Editor.WriteMessage(vbLf & acLyrTblRec.Name)

      Next

 

      '' Dispose of the transaction

  End Using

End Sub

C#

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

 

[CommandMethod("IterateLayers")]

public static void IterateLayers()

{

  // Get the current document and database, and start a transaction

  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  Database acCurDb = acDoc.Database;

 

  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())

  {

      // This example returns the layer table for the current database

      LayerTable acLyrTbl;

      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,

                                   OpenMode.ForRead) as LayerTable;

 

      // Step through the Layer table and print each layer name

      foreach (ObjectId acObjId in acLyrTbl)

      {

          LayerTableRecord acLyrTblRec;

          acLyrTblRec = acTrans.GetObject(acObjId,

                                          OpenMode.ForRead) as LayerTableRecord;

 

          acDoc.Editor.WriteMessage("/n" + acLyrTblRec.Name);

      }

 

      // Dispose of the transaction

  }

}

 

VBA/ActiveX Code Reference

 

Sub IterateLayers()

    ' Iterate through the collection

    On Error Resume Next

 

    Dim lay As AcadLayer

    Dim msg As String

    msg = ""

    For Each lay In ThisDrawing.Layers

        msg = msg + lay.Name + vbCrLf

    Next

 

    ThisDrawing.Utility.prompt msg

End Sub

Find the layer table record named MyLayer in the LayerTable object    LayerTable对象中查找名为MyLayer的图层表记录

The following example checks the LayerTable object to determine if the layer named MyLayer exists or not, and displays the appropriate message:

下面的例子检查LayerTable对象,确定名为MyLayer的图层是否存在,并显示相应消息:

VB.NET

Imports Autodesk.AutoCAD.Runtime

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.DatabaseServices

 

_

Public Sub FindMyLayer()

  '' Get the current document and database, and start a transaction

  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument

  Dim acCurDb As Database = acDoc.Database

 

  Using acTrans As Transaction = acCurDb.TransactionManager.StartTransaction()

      '' Returns the layer table for the current database

      Dim acLyrTbl As LayerTable

      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, _

                                   OpenMode.ForRead)

 

      '' Check to see if MyLayer exists in the Layer table

      If Not acLyrTbl.Has("MyLayer") Then

          acDoc.Editor.WriteMessage(vbLf & "'MyLayer' does not exist")

      Else

          acDoc.Editor.WriteMessage(vbLf & "'MyLayer' exists")

      End If

 

      '' Dispose of the transaction

  End Using

End Sub

C#

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

 

[CommandMethod("FindMyLayer")]

public static void FindMyLayer()

{

  // Get the current document and database, and start a transaction

  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  Database acCurDb = acDoc.Database;

 

  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())

  {

      // Returns the layer table for the current database

      LayerTable acLyrTbl;

      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,

                                   OpenMode.ForRead) as LayerTable;

 

      // Check to see if MyLayer exists in the Layer table

      if (acLyrTbl.Has("MyLayer") != true)

      {

          acDoc.Editor.WriteMessage("/n'MyLayer' does not exist");

      }

      else

      {

          acDoc.Editor.WriteMessage("/n'MyLayer' exists");

      }

 

      // Dispose of the transaction

  }

}

 

 

VBA/ActiveX Code Reference

 

Sub FindMyLayer()

    ' Use the Item method to find a layer named MyLayer

    On Error Resume Next

    Dim ABCLayer As AcadLayer

    Set ABCLayer = ThisDrawing.Layers("MyLayer")

    If Err <> 0 Then

        ThisDrawing.Utility.prompt "'MyLayer' does not exist"

    Else

        ThisDrawing.Utility.prompt "'MyLayer' exists"

    End If

End Sub

 

 

4Erase a Member of a Collection Object从集合对象中删除成员

Members from a collection object can be erased using the Erase method found on the member object. For example, the following code erases the layer MyLayer from the LayerTable object.

可以使用Erase方法删除集合对象成员。下例代码从LayerTable对象中删除图层MyLayer

Before you erase a layer from a drawing, you should make sure it can be safely removed. To determine if a layer or another named object such as a block or text style can be erased, you should use the Purge method. For information on the Purge method, see Purge Unreferenced Named Objects.

从图形中删除一个图层前,应先确定该图层能否被安全删除。我们用Purge方法确定是否可以删除图层、块、文字样式等这样的命名对象。关于Purge方法的内容,见清除不再被引用的命名对象。

VB.NET

Imports Autodesk.AutoCAD.Runtime

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.DatabaseServices

 

_

Public Sub RemoveMyLayer()

  '' Get the current document and database, and start a transaction

  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument

  Dim acCurDb As Database = acDoc.Database

 

  Using acTrans As Transaction = acCurDb.TransactionManager.StartTransaction()

      '' Returns the layer table for the current database

      Dim acLyrTbl As LayerTable

      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId, _

                                   OpenMode.ForRead)

 

      '' Check to see if MyLayer exists in the Layer table

      If acLyrTbl.Has("MyLayer") = True Then

          Dim acLyrTblRec As LayerTableRecord

          acLyrTblRec = acTrans.GetObject(acLyrTbl("MyLayer"), _

                                          OpenMode.ForWrite)

 

          Try

              acLyrTblRec.Erase()

              acDoc.Editor.WriteMessage(vbLf & "'MyLayer' was erased")

 

              '' Commit the changes

              acTrans.Commit()

          Catch

              acDoc.Editor.WriteMessage(vbLf & "'MyLayer' could not be erased")

          End Try

      Else

          acDoc.Editor.WriteMessage(vbLf & "'MyLayer' does not exist")

      End If

 

      '' Dispose of the transaction

  End Using

End Sub

C#

using Autodesk.AutoCAD.Runtime;

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

 

[CommandMethod("RemoveMyLayer")]

public static void RemoveMyLayer()

{

  // Get the current document and database, and start a transaction

  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  Database acCurDb = acDoc.Database;

 

  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())

  {

      // Returns the layer table for the current database

      LayerTable acLyrTbl;

      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,

                                   OpenMode.ForRead) as LayerTable;

 

      // Check to see if MyLayer exists in the Layer table

      if (acLyrTbl.Has("MyLayer") == true)

      {

          LayerTableRecord acLyrTblRec;

          acLyrTblRec = acTrans.GetObject(acLyrTbl["MyLayer"],

                                          OpenMode.ForWrite) as LayerTableRecord;

 

          try

          {

              acLyrTblRec.Erase();

              acDoc.Editor.WriteMessage("/n'MyLayer' was erased");

 

              // Commit the changes

              acTrans.Commit();

          }

          catch

          {

              acDoc.Editor.WriteMessage("/n'MyLayer' could not be erased");

          }

      }

      else

      {

          acDoc.Editor.WriteMessage("/n'MyLayer' does not exist");

      }

 

      // Dispose of the transaction

  }

}

 

 

VBA/ActiveX Code Reference

 

Sub RemoveMyLayer()

  On Error Resume Next

 

  '' Get the layer "MyLayer" from the Layers collection

  Dim ABCLayer As AcadLayer

  Set ABCLayer = ThisDrawing.Layers.Item("MyLayer")

 

  '' Check for an error, if no error occurs the layer exists

  If Err = 0 Then

 

    '' Delete the layer

    ABCLayer.Delete

 

    '' Clear the current error

    Err.Clear

 

    '' Get the layer again if it is found the layer could not be removed

    Set ABCLayer = ThisDrawing.Layers.Item("MyLayer")

 

    '' Check for error, if an error is encountered the layer was removed

    If Err <> 0 Then

      ThisDrawing.Utility.prompt "'MyLayer' was removed"

    Else

      ThisDrawing.Utility.prompt "'MyLayer' could not be removed"

    End If

  Else

    ThisDrawing.Utility.prompt "'MyLayer' does not exist"

  End If

End Sub

Once an object has been erased, you should not attempt to access the object again later in the program; otherwise an error will occur. The above sample tests to see if the object exists before it is accessed again. When a request to erase an object is made, you should check to see if the object exists with the Has method or use a Try statement to catch any exceptions that occur. For more information on handling exceptions, see Handle Errors.

一旦对象已删除,我们就不能试图在随后的程序中再访问该对象,否则就出错。上面的示例代码演示了在访问对象前检查对象是否存在。试图删除对象时,应该用Has方法检查其是否存在,或用Try语句捕捉可能发生的任何异常。有关处理异常的更多内容见 处理错误

 

 

你可能感兴趣的:(AutoCAD,.NET,API开发)