上次介绍了工程图里三种文本形式 http://blog.youkuaiyun.com/autodeskinventorapi/article/details/8524401。DWG图纸的块可以有属性文本。该文本是一种提示字串。Inventor API提供方法可访问到这些信息。
假定有这样一个AutoCAD图纸,其中有个块叫做myblock, 含有三个属性:aaa,bbb,ccc。最终显示的字串是:aaa-result, bbb-result,ccc-result. 以下VBA代码将获取相关信息:
Public Sub Test1()
Dim oDoc As DrawingDocument
Set oDoc = ThisApplication.ActiveDocument
Dim oTags() As String
Dim oValues() As String
Dim oAcadBlkDef As AutoCADBlockDefinition
Dim oCnt As Integer
'获取块中属性的tag和提示字串
Debug.Print ""
For Each oAcadBlkDef In oDoc.AutoCADBlockDefinitions
Call oAcadBlkDef.GetPromptTags(oTags, oValues)
Debug.Print "Block Name=" & oAcadBlkDef.Name
Dim i As Integer
For i = LBound(oTags) To UBound(oTags)
Debug.Print "Tag Name=" & oTags(i) & _
" Prompt= " & oValues(i)
Next
Next
'获取最终显示的字串
Debug.Print "----------------------"
Dim oAcadBlk As AutoCADBlock
For Each oAcadBlk In oDoc.ActiveSheet.AutoCADBlocks
Call oAcadBlk.GetPromptTextValues(oTags, oValues)
Debug.Print "Block Name=" & oAcadBlk.Name
For i = LBound(oTags) To UBound(oTags)
Debug.Print "Tag Name=" & oTags(i) & _
" Prompt= " & oValues(i)
Next
Next
Debug.Print ""
End Sub
结果是:
Block Name=myblock
Tag Name=CCC Prompt= ccc
Tag Name=BBB Prompt= bbb
Tag Name=AAA Prompt= aaa
----------------------
这段代码很简单,但用.NET时需要注意一个细节,即GetPromptTags或GetPromptTextValues传入的数组在.NET中必须初始化。而且需要点技巧。参看以下代码:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
' 获取当前运行的Inventor.
Dim invApp As Inventor.Application
invApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Inventor.Application")
If invApp.ActiveDocument.DocumentType <> Inventor.DocumentTypeEnum.kDrawingDocumentObject Then
MsgBox("Need to have a drawing document active")
Return
End If
' 获取当前工程图
Dim oDrawingDoc As Inventor.DrawingDocument
oDrawingDoc = invApp.ActiveDocument
' 得到AutoCADBlocks集合
Dim cAcadBlocks As Inventor.AutoCADBlocks
cAcadBlocks = oDrawingDoc.ActiveSheet.AutoCADBlocks
Dim AcadBlockName As String
AcadBlockName = "myblock"
' 获取我们关心的块
Dim oAcadBlock As Inventor.AutoCADBlock
oAcadBlock = cAcadBlocks.Item(AcadBlockName)
' 打印块的相关信息
Debug.Print(oAcadBlock.Scale)
Debug.Print(oAcadBlock.LineWeight)
Debug.Print(oAcadBlock.Name)
Debug.Print(oAcadBlock.AttributeSets.Count)
' 访问属性值
'正确
Dim sTags() AsString = New String() {}
Dim sAttr() AsString = New String() {}
'错误
'Dim sTags() As String = New Object() {}
'Dim sAttr() As String = New Object() {}
'如果预先知道属性个数,例如有23个,则以下初始化也对
' are no more than 23
'Dim sTags(23) As String
'Dim sAttr(23) As String
'不做任何初始化,错误
'Dim sTags() As String
'Dim sAttr() As String
'得到最终显示字串
oAcadBlock.GetPromptTextValues(sTags, sAttr)
Dim i AsInteger
Dim iCount AsInteger
iCount = UBound(sTags)
Debug.Print("icount = " & iCount)
' 依次打印
For i = 0 To iCount
MsgBox(sTags(i) & " = " & sAttr(i))
i = i + 1
Next
End Sub