Search code examples
vb.netautocad

Insert AutoCAD Block on a specific layer VB.NET


I'm trying to insert a block from another file and then change the layer of the block. I can get the block to insert into the modelspace but can't find a way to change it's layer. I'm hoping someone can help me out with the below code.

Thanks in advance.

        <CommandMethod("AddHardware")>
        Public Shared Sub Add_Hardware()

            Dim doc As Document = AutoCADApp.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor

            Using tr As Transaction = db.TransactionManager.StartTransaction()

                Dim pStrOpts As PromptStringOptions = New PromptStringOptions("NewFilename")
                pStrOpts.AllowSpaces = True
                
                Dim FileName As PromptResult = ed.GetString(pStrOpts)
                Dim Layer As String = ed.GetString("Layer").StringResult

                Dim ObjId As ObjectId
                Dim bt As BlockTable = db.BlockTableId.GetObject(OpenMode.ForRead)
                Dim btr As BlockTableRecord = bt(BlockTableRecord.ModelSpace).GetObject(OpenMode.ForWrite)

                Using dbInsert As New Database(False, True)
                    dbInsert.ReadDwgFile(FileName.StringResult, IO.FileShare.Read, True, "")
                    ObjId = db.Insert(Path.GetFileNameWithoutExtension(FileName.StringResult), dbInsert, True)
                End Using

                Dim curUCSMatrix As Matrix3d = doc.Editor.CurrentUserCoordinateSystem
                Dim curUCS As CoordinateSystem3d = curUCSMatrix.CoordinateSystem3d

                Dim BlkRef As New BlockReference(New Point3d(PositionX, PositionY, PositionZ), ObjId)

                BlkRef.TransformBy(Matrix3d.Rotation(RotateX, curUCS.Xaxis, New Point3d(PositionX, PositionY, PositionZ)))
                BlkRef.TransformBy(Matrix3d.Rotation(RotateY, curUCS.Yaxis, New Point3d(PositionX, PositionY, PositionZ)))
                BlkRef.TransformBy(Matrix3d.Rotation(RotateZ, curUCS.Zaxis, New Point3d(PositionX, PositionY, PositionZ)))

                btr.AppendEntity(BlkRef)
                tr.AddNewlyCreatedDBObject(BlkRef, True)
                tr.Commit()

            End Using

        End Sub


Solution

  • To change the layer of the block reference, simply set its Layer (or LayerId) property.

    BlkRef.Layer = LayerName