.NET中的AutoCAD -INSERT命令

时间:2013-06-27 13:42:22

标签: .net vb.net autocad-plugin objectarx

我的任务是将AutoCAD插件从VBA翻译成VB.NET,我现在有点卡住了。

我正在处理的命令创建一个新图层(或者如果它已经存在则选择它作为活动图层),然后执行2“-INSERT”命令,给出用户选择的点和dwg文件。然后,将前一个活动层重置为活动层。

insert-command看起来像这样:

-INSERT
C:\path\to\file.dwg
<point.x>,<point.y>,<point.z>
<documentScale>

注意:命令中的所有换行符都会添加为vbCR(不是vbCrLf)。

我的问题是,如何在.NET中针对ObjectARX实现相同的结果?我不能使用SendStringToExecute,因为它是异步的(没有回调),换句话说,一旦执行完毕,我就无法重置当前层。必须有一些方法可以在纯.NET代码中复制此功能,可能使用BlockTable,但我不知道如何。

我已尝试按照此处找到的文章:http://through-the-interface.typepad.com/through_the_interface/2006/08/import_blocks_f.html,但这根本没有对文档产生明显影响。我也尝试使用myDatabase.Insert(transform, otherDatabase, False),并且命令提示符说已经存在的块已经存在并因此被跳过,但我仍然没有看到任何变化。我不知道“-INSERT”命令在幕后实际上有多么神奇,但在.NET中复制它是否可行?或者它是否可以被称为普通方法(而不是作为发送给AutoCAD处理的文本命令)?

1 个答案:

答案 0 :(得分:5)

“通过界面”帖子中的代码示例导入块,但不将它们插入到图形中。您必须创建BlockReference并将其添加到模型空间。它还会插入文件中的所有块,而不是文件作为单个块。

以下是我用来将文件作为整个块导入的代码。此函数返回可以插入到图形中的块引用。

    Private Shared Function InsertFile(ByVal FileName as String, ByVal dwgdb As Database, ByVal tr As Transaction) As BlockReference

        Dim br As BlockReference
        Dim id As ObjectId

        'use a temporary database 
        Using TempDB As New Database(False, True)

            'Get block table
            Dim bt As BlockTable = tr.GetObject(dwgdb.BlockTableId, OpenMode.ForWrite, False)

            'Create unique block name
            Dim BlockName As String = FileName.Replace("\", "").Replace(":", "").Replace(".", "")

            'check if block already exists
            If Not bt.Has(BlockName) Then
                'check if file exists
                If IO.File.Exists(FileName) Then
                    'read in the file into the temp database
                    TempDB.ReadDwgFile(FileName, IO.FileShare.Read, True, Nothing)
                    'insert the tempdb into the current drawing db, id is the new block id
                    id = dwgdb.Insert(BlockName, TempDB, True)
                Else
                    'Throw exception for missing file 
                    Throw New System.Exception(String.Format("File {0} is not found for library item {1}", FileName, item.PartNo))
                End If

            Else
                id = bt.Item(BlockName)
            End If

            'create a new block reference
            br = New BlockReference(New Point3d(0, 0, 0), id)
        End Using

        Return br


    End Function

这是使用该函数将块插入文件的示例。在这个例子中,我使用一个夹具,它允许用户将对象放到他们想要的位置,否则你可以设置位置。

      ' Get Editor
        Dim ed As Editor = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor
        ' Get Database
        Dim dwg As Database = ed.Document.Database

        'Lock document
        Using dl As DocumentLock = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.LockDocument()

            '### Changed Try Finally to using, try was hiding errors
            'Begin Transaction
            Using trans As Transaction = dwg.TransactionManager.StartTransaction()

                Dim blockRef As BlockReference = InsertFile(FileName, dwg, trans)

                'check if layer exists/create
                AcadUtil.AcadFunctions.CheckLayer(LayerName, trans, dwg)
                blockRef.Layer = LayerName

                'set focus to the editor
                Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView()

                'have the user pick insert point
                Dim BlockMove As New AcadJigs.JigBlockMove(blockRef, False, 0)
                ed.Drag(BlockMove)
                'optionally you could just set the .Position of the block reference


                ' add it to the current space, first open the current space for write
                Dim btr As BlockTableRecord = trans.GetObject(dwg.CurrentSpaceId, OpenMode.ForWrite, True, True)

                ' Add block reference to current space
                btr.AppendEntity(blockRef)

                'Capture the handle
                handle = blockRef.Handle.Value.ToString

                ' remember to tell the transaction about the new block reference so that the transaction can autoclose it
                trans.AddNewlyCreatedDBObject(blockRef, True)

                'commit the transaction
                trans.Commit()

            End Using

        End Using

这里也是我调用的CheckLayer函数。

    Public Shared Sub CheckLayer(ByVal Name As String, ByVal tr As Transaction, ByVal dwg As Database)


        Dim lt As LayerTable = CType(tr.GetObject(dwg.LayerTableId, OpenMode.ForWrite), LayerTable)

        If lt.Has(Name) Then
            Return
        Else
            Dim ly As New LayerTableRecord
            ly.Name = Name
            lt.Add(ly)
            tr.AddNewlyCreatedDBObject(ly, True)
        End If

    End Sub

正如笔记一样,Kean的博客是一个很好的资源,我几乎从那里学到了所有上述代码。

为了完整起见,这里是插入代码中的Jig类i引用,

 Class JigBlockMove
        Inherits EntityJig

        Private _CenterPt As Point3d
        Private _ActualPoint As Point3d
        Private _LockZ As Boolean
        Private _Z As Double

        Public ReadOnly Property SelectedPoint() As Point3d
            Get
                Return _ActualPoint
            End Get
        End Property

        Public Sub New(ByVal BlockRef As BlockReference, ByVal LockZ As Boolean, ByVal Z As Double)
            MyBase.New(BlockRef)
            _CenterPt = BlockRef.Position
            _LockZ = LockZ
            _Z = Z
        End Sub

        Protected Overloads Overrides Function Sampler(ByVal prompts As JigPrompts) As SamplerStatus
            Dim jigOpts As New JigPromptPointOptions()
            jigOpts.UserInputControls = (UserInputControls.Accept3dCoordinates Or UserInputControls.NoZeroResponseAccepted Or UserInputControls.NoNegativeResponseAccepted)
            jigOpts.Message = vbLf & "Enter insert point: "
            Dim dres As PromptPointResult = prompts.AcquirePoint(jigOpts)
            If _ActualPoint = dres.Value Then
                Return SamplerStatus.NoChange
            Else
                _ActualPoint = dres.Value
            End If

            Return SamplerStatus.OK
        End Function

        Protected Overloads Overrides Function Update() As Boolean
            If _LockZ Then
                _CenterPt = New Point3d(_ActualPoint.X, _ActualPoint.Y, _Z)
            Else
                _CenterPt = _ActualPoint
            End If

            Try
                DirectCast(Entity, BlockReference).Position = _CenterPt
            Catch generatedExceptionName As System.Exception
                Return False
            End Try

            Return True
        End Function

        Public Function GetEntity() As Entity
            Return Entity
        End Function

    End Class

关于在.NET ObjectARX中工作的一个注意事项,AutoCAD的单线程特性存在问题,并且.NET垃圾收集器在单独的线程上运行。如果创建任何未添加到数据库的临时AutoCAD对象,则必须明确调用.Dispose(),否则AutoCAD可能会崩溃!崩溃似乎也是随机的,因为它将由垃圾收集器线程触发。请参阅此帖子http://through-the-interface.typepad.com/through_the_interface/2008/06/cleaning-up-aft.html