コード例 #1
0
ファイル: AcadCmds.cs プロジェクト: presscad/Learn_objectARX
        public void DrawLine1()
        {
            Database db = AcadApp.Application.DocumentManager.MdiActiveDocument.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable blk_tbl = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                if (null == blk_tbl)
                {
                    return;
                }

                BlockTableRecord model_space = tr.GetObject(blk_tbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                if (null == model_space)
                {
                    return;
                }

                Line line = new Line(new AcadGeo.Point3d(0.0, 0.0, 0.0), new AcadGeo.Point3d(1.0, 1.0, 0.0));

                model_space.UpgradeOpen();
                model_space.AppendEntity(line);

                tr.AddNewlyCreatedDBObject(line, true);

                tr.Commit();
            }
        }
コード例 #2
0
        public BlockReference createAnonymousBlock(BlockTable bt, List <Entity> entities, BlockTableRecord spaceRecord, Transaction tr, Database db)
        {
            BlockTableRecord btr = new BlockTableRecord();

            spaceRecord.UpgradeOpen();
            ObjectId btrId = bt.Add(btr);

            tr.AddNewlyCreatedDBObject(btr, true);


            ObjectIdCollection obIdCol = new ObjectIdCollection();

            foreach (Entity ent in entities)
            {
                //ent.TransformBy(matrix);
                obIdCol.Add(ent.ObjectId);
            }

            IdMapping mapping = new IdMapping();

            db.DeepCloneObjects(obIdCol, btrId, mapping, false);

            BlockReference bref = new BlockReference(Point3d.Origin, btrId);

            spaceRecord.AppendEntity(bref);
            tr.AddNewlyCreatedDBObject(bref, true);
            spaceRecord.DowngradeOpen();

            foreach (Entity ent in entities)
            {
                ent.Erase();
            }
            return(bref);
        }
コード例 #3
0
ファイル: CADops.cs プロジェクト: peggylin-hub/CADworks
        /// <summary>
        /// Insert block into layout
        /// </summary>
        /// <param name="db"></param>
        /// <param name="layoutName"></param>
        /// <param name="blockName"></param>
        /// <param name="insPnt"></param>
        /// <returns></returns>
        public static bool InsertBlock(Database db, string layoutName, string blockName, Point3d insPnt)
        {
            LayoutManager lm = LayoutManager.Current;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                if (!bt.Has(blockName))
                {
                    return(false); ////// need to load the block
                }
                //get the block id
                ObjectId         blkId = bt[blockName];
                BlockTableRecord btr   = null;
                if (string.IsNullOrEmpty(layoutName))
                {
                    btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                }
                else
                {
                    ObjectId layoutId = lm.GetLayoutId(layoutName);
                    Layout   layout   = tr.GetObject(layoutId, OpenMode.ForRead) as Layout;
                    btr = tr.GetObject(layout.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;
                }

                //insert the block
                BlockReference blkRef = new BlockReference(insPnt, blkId);
                btr.UpgradeOpen();
                btr.AppendEntity(blkRef);
                tr.AddNewlyCreatedDBObject(blkRef, true);
                tr.Commit();
            }
            return(true);
        }
コード例 #4
0
ファイル: AcadCmds.cs プロジェクト: presscad/Learn_objectARX
        public void DrawLine3()
        {
            Database db = AcadApp.Application.DocumentManager.MdiActiveDocument.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable blk_tbl = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                if (null == blk_tbl)
                {
                    return;
                }

                BlockTableRecord model_space = tr.GetObject(blk_tbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                if (null == model_space)
                {
                    return;
                }

                DoSomething(model_space);                 //error here

                Line line = new Line();

                //good coding habit
                line.StartPoint = FindoutStartPoint();
                line.EndPoint   = FindoutEndPoint();

                model_space.UpgradeOpen();
                model_space.AppendEntity(line);

                tr.AddNewlyCreatedDBObject(line, true);

                tr.Commit();
            }
        }
コード例 #5
0
        public BlockReference copyDynamicBlock(BlockTableRecord spaceRecord, ref BlockReference bref, ref BlockTableRecord br, Transaction tr)
        {
            BlockReference newbref = copyBlockReference(ref bref, ref br);

            //newbref.UpgradeOpen();
            //spaceRecord.DowngradeOpen();
            spaceRecord.UpgradeOpen();
            spaceRecord.AppendEntity(newbref);
            tr.AddNewlyCreatedDBObject(newbref, true);
            spaceRecord.DowngradeOpen();

            //newbref.Visible = false;

            for (int i = 0; i < bref.DynamicBlockReferencePropertyCollection.Count; i++)
            {
                for (int j = 0; j < newbref.DynamicBlockReferencePropertyCollection.Count; j++)
                {
                    if (!newbref.DynamicBlockReferencePropertyCollection[j].ReadOnly &&
                        !bref.DynamicBlockReferencePropertyCollection[i].ReadOnly &&
                        newbref.DynamicBlockReferencePropertyCollection[j].PropertyName == bref.DynamicBlockReferencePropertyCollection[i].PropertyName
                        )
                    {
                        newbref.DynamicBlockReferencePropertyCollection[j].Value = bref.DynamicBlockReferencePropertyCollection[i].Value;
                    }
                }
            }
            return(newbref);
        }
コード例 #6
0
        public static bool EraseBlk(ObjectId blkId)
        {
            bool blkIsErased = false;

            if (blkId.IsNull)
            {
                return(false);
            }

            Database db = blkId.Database;

            if (db == null)
            {
                return(false);
            }

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord blk = (BlockTableRecord)tr.GetObject(blkId, OpenMode.ForRead);
                var blkRefs          = blk.GetBlockReferenceIds(true, true);
                if (blkRefs == null || blkRefs.Count == 0)
                {
                    blk.UpgradeOpen();
                    blk.Erase();
                    blkIsErased = true;
                }
                tr.Commit();
            }
            return(blkIsErased);
        }
コード例 #7
0
        public static ObjectId InsertBlock(Database db, string loName, string blkName, Point3d insPt)
        {
            ObjectId RtnObjId = ObjectId.Null;

            using (Transaction Trans = db.TransactionManager.StartTransaction())
            {
                DBDictionary LoDict = Trans.GetObject(db.LayoutDictionaryId, OpenMode.ForRead) as DBDictionary;
                foreach (DictionaryEntry de in LoDict)
                {
                    if (string.Compare((string)de.Key, loName, true).Equals(0))
                    {
                        Layout           Lo          = Trans.GetObject((ObjectId)de.Value, OpenMode.ForWrite) as Layout;
                        BlockTable       BlkTbl      = Trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        BlockTableRecord LoRec       = Trans.GetObject(Lo.BlockTableRecordId, OpenMode.ForRead) as BlockTableRecord;
                        ObjectId         BlkTblRecId = GetNonErasedTableRecordId(BlkTbl.Id, blkName);
                        if (BlkTblRecId.IsNull)
                        {
                            string BlkPath = HostApplicationServices.Current.FindFile(blkName + ".dwg", db, FindFileHint.Default);
                            if (string.IsNullOrEmpty(BlkPath))
                            {
                                return(RtnObjId);
                            }
                            BlkTbl.UpgradeOpen();
                            using (Database tempDb = new Database(false, true))
                            {
                                tempDb.ReadDwgFile(BlkPath, FileShare.Read, true, null);
                                db.Insert(blkName, tempDb, false);
                            }
                            BlkTblRecId = GetNonErasedTableRecordId(BlkTbl.Id, blkName);
                        }
                        LoRec.UpgradeOpen();
                        BlockReference BlkRef = new BlockReference(insPt, BlkTblRecId);
                        LoRec.AppendEntity(BlkRef);
                        Trans.AddNewlyCreatedDBObject(BlkRef, true);
                        BlockTableRecord BlkTblRec = Trans.GetObject(BlkTblRecId, OpenMode.ForRead) as BlockTableRecord;
                        if (BlkTblRec.HasAttributeDefinitions)
                        {
                            foreach (ObjectId objId in BlkTblRec)
                            {
                                AttributeDefinition AttDef = Trans.GetObject(objId, OpenMode.ForRead) as AttributeDefinition;
                                if (AttDef != null)
                                {
                                    AttributeReference AttRef = new AttributeReference();
                                    AttRef.SetAttributeFromBlock(AttDef, BlkRef.BlockTransform);
                                    BlkRef.AttributeCollection.AppendAttribute(AttRef);
                                    Trans.AddNewlyCreatedDBObject(AttRef, true);
                                }
                            }
                        }
                        Trans.Commit();
                    }
                }
            }
            return(RtnObjId);
        }
コード例 #8
0
        /// <summary>
        /// Вставка примитива в блок (должна быть запущена транзакция)
        /// </summary>
        /// <param name="ent">Примитив</param>
        /// <param name="btr">Блок</param>
        public static ObjectId Append([NotNull] this Entity ent, [NotNull] BlockTableRecord btr)
        {
            if (!btr.IsWriteEnabled)
            {
                btr.UpgradeOpen();
            }
            var id = btr.AppendEntity(ent);

            btr.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(ent, true);
            return(id);
        }
コード例 #9
0
ファイル: StructTools.cs プロジェクト: Nicool3/GLTools
 /// <summary>
 /// 删除多段线中的多余点并将应闭合的多段线闭合
 /// </summary>
 public static void PLinePurge(this Database db, ObjectId id)
 {
     using (Transaction trans = db.TransactionManager.StartTransaction())
     {
         // 打开块表
         BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
         // 打开块表记录
         BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
         // 获取图形对象
         Entity ent = trans.GetObject(id, OpenMode.ForWrite) as Entity;
         if (ent.GetType() == typeof(Polyline))
         {
             Polyline  pline     = ent as Polyline;
             PLineData plinedata = db.GetPLineData(id);
             /// 删除多段线中的多余点
             if (plinedata.VertexCount > 2)
             {
                 // 为避免下标出现问题, 从下标最大处开始遍历
                 for (int i = plinedata.VertexCount - 2; i > 0; i--)
                 {
                     if (plinedata.Vectors[i - 1] == plinedata.Vectors[i])
                     {
                         btr.UpgradeOpen();
                         pline.RemoveVertexAt(i);
                         btr.DowngradeOpen();
                     }
                 }
             }
             // 重新读取
             plinedata = db.GetPLineData(id);
             if (plinedata.VertexPoints[0] == plinedata.VertexPoints[plinedata.VertexCount - 1])
             {
                 btr.UpgradeOpen();
                 pline.Closed = true;
                 pline.RemoveVertexAt(plinedata.VertexCount - 1);
                 btr.DowngradeOpen();
             }
         }
         trans.Commit();
     }
 }
コード例 #10
0
        fixXrefs()
        {
            DBObject DbObj;

            try
            {
                using (Transaction tr = BaseObjs.startTransactionDb())
                {
                    SelectionSet SS = Base_Tools45.Select.buildSSet(typeof(BlockReference), true);
                    if (SS == null)
                    {
                        return;
                    }

                    foreach (SelectedObject ssObj in SS)
                    {
                        DbObj = ssObj.ObjectId.GetObject(OpenMode.ForRead);

                        if (DbObj is BlockReference)
                        {
                            BlockReference   BR  = (BlockReference)DbObj;
                            ObjectId         id  = BR.BlockTableRecord;
                            BlockTableRecord Btr = (BlockTableRecord)id.GetObject(OpenMode.ForRead);
                            string           nameLayer;
                            if (Btr.XrefStatus == XrefStatus.Resolved)
                            {
                                if (Btr.Name.Substring(1, 1) != "x")
                                {
                                    nameLayer = string.Format("_{0}", Btr.Name);
                                    Btr.UpgradeOpen();
                                    Btr.Name = string.Format("x{0}", Btr.Name);
                                }
                                else
                                {
                                    nameLayer = String.Format("_{0}", Btr.Name.Substring(2));
                                }
                                if (BR.Layer != nameLayer)
                                {
                                    BR.UpgradeOpen();
                                    Layer.manageLayers(nameLayer);
                                    BR.Layer = nameLayer;
                                }
                            }
                        }
                    }
                    tr.Commit();
                }
            }
            catch (System.Exception ex)
            {
                BaseObjs.writeDebug(ex.Message + " xRef.cs: line: 307");
            }
        }
コード例 #11
0
        public static void Example_2()
        {
            Document active_document = Application.DocumentManager.MdiActiveDocument;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager transaction_manager = HostApplicationServices.WorkingDatabase.TransactionManager;

            using (active_document.LockDocument())
            {
                using (Transaction transaction = transaction_manager.StartTransaction())
                {
                    // Enclosing creation of DBText object in using construction for guaranteed calling.
                    // We will add this object through transaction via AddNewlyCreatedDBObject().
                    // And in this case there would be no need in direct disposing of this object.
                    // But if we wouldn't come to adding object line (for example, if an exception will be thrown)
                    // via transaction then the object won't become managed by transaction
                    // and Dispose() will be needed (and that will be provided indirectly
                    // by putting the objects creation in using statement).
                    using (DBText text = new DBText())
                    {
                        BlockTable block_table = transaction.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;

                        // Here the text object is not yet managed by transaction.
                        // And if we return from method here without putting the object in using
                        // the wouldn't be disposed. That's why we need to put the object in using statement.
                        if (!block_table.Has(BlockTableRecord.ModelSpace))
                        {
                            return;
                        }

                        BlockTableRecord block_table_record = transaction.GetObject(block_table[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                        block_table_record.UpgradeOpen();

                        if (!block_table_record.IsWriteEnabled)
                        {
                            active_document.Editor.WriteMessage("Can't open for write");
                            return;
                        }

                        text.TextString = "Hello World";
                        text.Position   = new Point3d(10, 10, 0);

                        block_table_record.AppendEntity(text);
                        // Here the object becomes managed by transaction.
                        transaction.AddNewlyCreatedDBObject(text, true);

                        transaction.Commit();
                    }
                }
            }
        }
コード例 #12
0
        private void DeleteBlocksWithPrefix(string prefix, Transaction tr)
        {
            BlockTable blockTable = tr.GetObject(Doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable;

            foreach (ObjectId blockId in blockTable)
            {
                BlockTableRecord block = (BlockTableRecord)tr.GetObject(blockId, OpenMode.ForRead);
                if (block.Name.StartsWith(prefix))
                {
                    block.UpgradeOpen();
                    block.Erase();
                }
            }
        }
コード例 #13
0
            static public void RegionToPolyline(ObjectId regId)
            {
                Document doc = Active.Document;

                global::Autodesk.AutoCAD.DatabaseServices.Database db = doc.Database;
                Editor ed = doc.Editor;

                Transaction tr =
                    doc.TransactionManager.StartTransaction();

                using (tr)
                {
                    BlockTable bt =
                        (BlockTable)tr.GetObject(
                            db.BlockTableId,
                            OpenMode.ForRead);
                    BlockTableRecord btr =
                        (BlockTableRecord)tr.GetObject(
                            bt[BlockTableRecord.ModelSpace],
                            OpenMode.ForRead);

                    Region reg =
                        tr.GetObject(
                            regId,
                            OpenMode.ForRead) as Region;


                    if (reg != null)
                    {
                        DBObjectCollection objs =
                            PolylineFromRegion(reg);

                        // Append our new entities to the database

                        btr.UpgradeOpen();

                        foreach (Entity ent in objs)
                        {
                            btr.AppendEntity(ent);
                            tr.AddNewlyCreatedDBObject(ent, true);
                        }

                        // Finally we erase the original region

                        reg.UpgradeOpen();
                        reg.Erase();
                    }
                    tr.Commit();
                }
            }
コード例 #14
0
        public static void Demo_OpenCloseTransaction()
        {
            try
            {
                Circle c = null;
                using (Transaction t = Active.Database.TransactionManager.StartOpenCloseTransaction())
                {
                    c            = new Circle();
                    c.ColorIndex = 3;
                    c.Radius     = 200;
                    c.Center     = new Point3d(0, 0, 0);



                    BlockTable block_table = t.GetObject(HostApplicationServices.WorkingDatabase.BlockTableId, OpenMode.ForRead) as BlockTable;

                    if (!block_table.Has(BlockTableRecord.ModelSpace))
                    {
                        return;
                    }

                    BlockTableRecord block_table_record = t.GetObject(block_table[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                    block_table_record.UpgradeOpen();

                    if (!block_table_record.IsWriteEnabled)
                    {
                        Active.WriteMessage("Can't open for write");
                        return;
                    }
                    block_table_record.AppendEntity(c);



                    t.AddNewlyCreatedDBObject(c, true);


                    c.Dispose();
                }

                Active.WriteMessage(c.Radius.ToString());

                c.UpgradeOpen();
                c.Radius = 300;
            }
            catch (System.Exception ex)
            {
                ExceptionHandler.WriteToCommandLine(ex);
            }
        }
コード例 #15
0
        public Line copyLine(BlockTableRecord spaceRecord, ref Line line, Transaction tr)
        {
            Line newLine = new Line();

            newLine.StartPoint = line.StartPoint;
            newLine.EndPoint   = line.EndPoint;
            newLine.Normal     = line.Normal;
            newLine.Layer      = swallLayer;
            spaceRecord.UpgradeOpen();
            spaceRecord.AppendEntity(newLine);
            tr.AddNewlyCreatedDBObject(newLine, true);
            spaceRecord.DowngradeOpen();

            return(newLine);
        }
コード例 #16
0
 public static void InnerTransform(this BlockReference br, Matrix3d transform)
 {
     Tools.StartTransaction(() =>
     {
         br = br.Id.GetObjectForRead <BlockReference>();
         //br = br.GetAnonymClone(br.Position).GetObjectForRead<BlockReference>();
         BlockTableRecord btr = br.BlockTableRecord.GetObjectForRead <BlockTableRecord>();
         btr.UpgradeOpen();
         foreach (ObjectId id in btr)
         {
             Entity ent = id.GetObjectForWrite <Entity>();
             ent.TransformBy(transform);
         }
         br.UpgradeOpen();
         br.RecordGraphicsModified(true);
         br.Database.TransactionManager.QueueForGraphicsFlush();
     });
 }
コード例 #17
0
        internal static void AddingAttributeToBlock(string blkName)
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);

                if (!bt.Has(blkName))
                {
                    ed.WriteMessage("\nBlock definition PART does not  exist");
                    return;
                }

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[blkName], OpenMode.ForRead, false);

                // location of the AttributeDefinition in the
                // block definition
                Point3d ptloc = new Point3d(0, 2, 0);

                // create a AttributeDefinition
                // specify the text,tag and prompt
                string attrValue = "NEW VALUE ADDED";
                string attrTag   = "MYTAG";
                string strprompt = "Enter a new value";

                // used current text style
                AttributeDefinition attDef = new AttributeDefinition(ptloc, attrValue, attrTag, strprompt, db.Textstyle);
                attDef.Height     = 0.12;
                attDef.Layer      = "0";
                attDef.Color      = Autodesk.AutoCAD.Colors.Color.FromColorIndex(ColorMethod.ByAci, 0);
                attDef.LinetypeId = db.ContinuousLinetype;

                // append the AttributeDefinition to the definition
                btr.UpgradeOpen();
                btr.AppendEntity(attDef);
                tr.AddNewlyCreatedDBObject(attDef, true);
                btr.DowngradeOpen();
                tr.Commit();
            }
        }
コード例 #18
0
ファイル: AcadCmds.cs プロジェクト: presscad/Learn_objectARX
        public void DrawLine1()
        {
            Database db = AcadApp.Application.DocumentManager.MdiActiveDocument.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable blk_tbl = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                if (null == blk_tbl)
                {
                    return;
                }

                BlockTableRecord model_space = tr.GetObject(blk_tbl[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                if (null == model_space)
                {
                    return;
                }

                DoSomething(model_space);                 //error here

                Line line = new Line();

                //bad coding habit

                /*
                 * calculate something here to findout the start point of the line
                 */
                line.StartPoint = new AcadGeo.Point3d(0.0, 0.0, 0.0);

                /*
                 * Calculate something here to findout the end point of the line
                 */
                line.EndPoint = new AcadGeo.Point3d(10.0, 0.0, 0.0);

                model_space.UpgradeOpen();
                model_space.AppendEntity(line);

                tr.AddNewlyCreatedDBObject(line, true);

                tr.Commit();
            }
        }
コード例 #19
0
ファイル: Funcs.cs プロジェクト: presscad/Learn_objectARX
        //public - protected - private
        static public void AddNewEnt(Entity ent)
        {
            Database db = GetActiveDb();

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTableRecord model_space = GetModelSpace(tr);
                if (null == model_space)
                {
                    return;
                }

                model_space.UpgradeOpen();
                model_space.AppendEntity(ent);

                tr.AddNewlyCreatedDBObject(ent, true);

                tr.Commit();
            }
        }
コード例 #20
0
ファイル: StructTools.cs プロジェクト: Nicool3/GLTools
 /// <summary>
 /// 修改矩形宽度
 /// </summary>
 public static void SetRectangleWidth(this Database db, ObjectId id, double newWidth)
 {
     if (db.IsRectangle(id))
     {
         RectangleData data      = db.GetRectangleData(id);
         int           baseIndex = data.BasePointIndex;
         Point3d       basePoint = data.BasePoint;
         bool          clockWise = data.IsClockWise;
         double        width     = data.Width;
         double        height    = data.Height;
         using (Transaction trans = db.TransactionManager.StartTransaction())
         {
             // 打开块表
             BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
             // 打开块表记录
             BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
             // 获取图形对象
             Entity ent = trans.GetObject(id, OpenMode.ForWrite) as Entity;
             if (ent.GetType() == typeof(Polyline))
             {
                 Polyline pline = ent as Polyline;
                 btr.UpgradeOpen();
                 pline.SetPointAt(baseIndex, new Point2d(basePoint.X - newWidth / 2, basePoint.Y));
                 if (clockWise)
                 {
                     pline.SetPointAt((baseIndex + 1) % 4, new Point2d(basePoint.X - newWidth / 2, basePoint.Y + height));
                     pline.SetPointAt((baseIndex + 2) % 4, new Point2d(basePoint.X + width + newWidth / 2, basePoint.Y + height));
                     pline.SetPointAt((baseIndex + 3) % 4, new Point2d(basePoint.X + width + newWidth / 2, basePoint.Y));
                 }
                 else
                 {
                     pline.SetPointAt((baseIndex + 1) % 4, new Point2d(basePoint.X + width + newWidth / 2, basePoint.Y));
                     pline.SetPointAt((baseIndex + 2) % 4, new Point2d(basePoint.X + width + newWidth / 2, basePoint.Y + height));
                     pline.SetPointAt((baseIndex + 3) % 4, new Point2d(basePoint.X - newWidth / 2, basePoint.Y + height));
                 }
                 btr.DowngradeOpen();
             }
             trans.Commit();
         }
     }
 }
コード例 #21
0
ファイル: Program.cs プロジェクト: daqi5258/AutoCad
        public void drawLine()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable       bt  = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead) as BlockTableRecord;
                btr.UpgradeOpen();
                Point3d startPoint = new Point3d(100, 100, 0);
                Point3d endPoint   = new Point3d(200, 200, 0);
                Line    line       = new Line(startPoint, endPoint);
                btr.AppendEntity(line);
                trans.AddNewlyCreatedDBObject(line, true);
                doc.Editor.WriteMessage("hello CAD");
                //doc.SendStringToExecute("._break 150,150,100 160,160,100 ",true,false,false);
                doc.SendStringToExecute("._zoom all ", true, false, false);
                trans.Commit();
            }
        }
コード例 #22
0
 public static void EraseBolckTableRecord(this BlockTableRecord btr)
 {
     Tools.StartTransaction(() =>
     {
         if (btr.Id != ObjectId.Null)
         {
             btr = btr.Id.GetObjectForRead <BlockTableRecord>(false);
             if (!btr.IsErased)
             {
                 btr.UpgradeOpen();
                 using (BlockTableRecordEnumerator enumerator = btr.GetEnumerator())
                 {
                     while (enumerator.MoveNext())
                     {
                         enumerator.Current.GetObject((OpenMode)OpenMode.ForWrite).Erase();
                     }
                 }
                 btr.DowngradeOpen();
             }
         }
     });
 }
コード例 #23
0
        public Line CopyLine(BlockTableRecord spaceRecord, ref Line line, Transaction tr)
        {
            Line newLine = new Line();

            newLine.StartPoint = line.StartPoint;
            newLine.EndPoint   = line.EndPoint;
            newLine.Normal     = line.Normal;
            //newLine.Layer = line.Layer.Split('|').Last();
            newLine.Layer = frameBlockAboveLayer;
            //newLine.Linetype = line.Linetype;
            newLine.Linetype      = "SWALL";
            newLine.PlotStyleName = line.PlotStyleName;
            newLine.Color         = line.Color;
            newLine.ColorIndex    = line.ColorIndex;

            spaceRecord.UpgradeOpen();
            spaceRecord.AppendEntity(newLine);
            tr.AddNewlyCreatedDBObject(newLine, true);
            spaceRecord.DowngradeOpen();

            return(newLine);
        }
コード例 #24
0
        // Erase the anonymous blocks referenced by an object

        private static void EraseReferencedAnonBlocks(
            Transaction tr, DBObject obj
            )
        {
            var refFiler = new ReferenceFiler();

            obj.DwgOut(refFiler);

            // Loop through the references and erase any
            // anonymous block definitions
            //
            foreach (ObjectId refid in refFiler.HardPointerIds)
            {
                BlockTableRecord btr =
                    tr.GetObject(refid, OpenMode.ForRead) as BlockTableRecord;
                if (btr != null && btr.IsAnonymous)
                {
                    btr.UpgradeOpen();
                    btr.Erase();
                }
            }
        }
コード例 #25
0
 public static void Update(this BlockTableRecord btr)
 {
     Tools.StartTransaction(() =>
     {
         if (btr.Id != ObjectId.Null)
         {
             btr = btr.Id.GetObjectForRead <BlockTableRecord>(false);
             btr.UpgradeOpen();
             foreach (ObjectId id in btr.GetBlockReferenceIds(true, false))
             {
                 BlockReference br = id.GetObjectForWrite <BlockReference>(false);
                 br.RecordGraphicsModified(true);
                 btr.Database.TransactionManager.QueueForGraphicsFlush();
             }
             foreach (ObjectId id in btr.GetAnonymousBlockIds())
             {
                 BlockReference br = id.GetObjectForWrite <BlockReference>(false);
                 br.RecordGraphicsModified(true);
                 btr.Database.TransactionManager.QueueForGraphicsFlush();
             }
         }
     });
 }
コード例 #26
0
ファイル: BlockCmd.cs プロジェクト: VB6Hobbyst7/AutoCad-1
 private void _eraseBolckTableRecord()
 {
     using (Transaction trans = Tools.StartTransaction())
     {
         if (this.BlockTableRecordId != ObjectId.Null)
         {
             BlockTableRecord btr = (BlockTableRecord)this.BlockTableRecordId.GetObject(OpenMode.ForRead, true, true);
             if (!btr.IsErased)
             {
                 btr.UpgradeOpen();
                 using (BlockTableRecordEnumerator enumerator = btr.GetEnumerator())
                 {
                     while (enumerator.MoveNext())
                     {
                         enumerator.Current.GetObject((OpenMode)OpenMode.ForWrite).Erase();
                     }
                 }
                 trans.Commit();
                 _entities = new List <Entity>();
             }
         }
     }
 }
コード例 #27
0
        private static AttributeDefinition defineAtrDefTypeFlat(BlockTableRecord btrApart, string typeFlatValue)
        {
            // Поиск существующего атрибута типа квартиры
            if (btrApart.HasAttributeDefinitions)
            {
                foreach (var idEnt in btrApart)
                {
                    if (idEnt.ObjectClass.Name != "AcDbAttributeDefinition")
                    {
                        continue;
                    }
                    var atrDef = idEnt.GetObject(OpenMode.ForRead, false, true) as AttributeDefinition;
                    if (atrDef == null || !atrDef.Tag.Equals(Options.Instance.ApartmentTypeFlatParameter))
                    {
                        continue;
                    }
                    atrDef.UpgradeOpen();
                    atrDef.TextString          = typeFlatValue;
                    atrDef.Invisible           = true;
                    atrDef.LockPositionInBlock = true;
                    atrDef.DowngradeOpen();
                    return(atrDef);
                }
            }
            // Создание определения атрибута и добавление в блок
            AttributeDefinition atrDefTypeFlat = new AttributeDefinition(Point3d.Origin, typeFlatValue,
                                                                         Options.Instance.ApartmentTypeFlatParameter,
                                                                         "Параметр типа квартиры - Студия, 1комн, и т.д.", btrApart.Database.GetTextStylePIK());

            atrDefTypeFlat.Invisible           = true;
            atrDefTypeFlat.LockPositionInBlock = true;
            btrApart.UpgradeOpen();
            btrApart.AppendEntity(atrDefTypeFlat);
            btrApart.Database.TransactionManager.TopTransaction.AddNewlyCreatedDBObject(atrDefTypeFlat, true);
            btrApart.DowngradeOpen();
            return(atrDefTypeFlat);
        }
コード例 #28
0
        public Polyline CopyPolyline(BlockTableRecord spaceRecord, ref Polyline pline, Transaction tr)
        {
            Polyline newpLine = new Polyline();
            int      max      = pline.NumberOfVertices;

            for (int i = 0; i < max; i++)
            {
                newpLine.AddVertexAt(i, pline.GetPoint2dAt(i), pline.GetBulgeAt(i), pline.GetStartWidthAt(i), pline.GetEndWidthAt(i));
            }

            newpLine.Closed = pline.Closed;
            //newpLine.Layer = pline.Layer.Split('|').Last();
            newpLine.Layer      = frameBlockAboveLayer;
            newpLine.Normal     = pline.Normal;
            newpLine.Color      = pline.Color;
            newpLine.ColorIndex = pline.ColorIndex;

            spaceRecord.UpgradeOpen();
            spaceRecord.AppendEntity(newpLine);
            tr.AddNewlyCreatedDBObject(newpLine, true);
            spaceRecord.DowngradeOpen();

            return(newpLine);
        }
コード例 #29
0
        static public void InsertBlocksByExcel()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;

            string excelFile = "D:\\dwgBlock_list.xlsx";

            Dictionary <string, List <string> > data = Excel.getDwgBlockList(excelFile);

            string        blockTemplate = @"D:\_PROJECTs\60614740-MascotTunnel\_blocks\CADtemplate.dwg";
            List <string> blockRequired = new List <string>()
            {
                "RMS_TfNSW_DESIGN-BLK-00-0000-GE-ADM_A1",
                "RMS_TfNSW_DESIGN-BLK-00-0000-GE-ATT_A1"
            };
            //load block template file database
            Database sourceDb = new Database(false, true);

            if (File.Exists(blockTemplate))
            {
                //open block template file to read
                sourceDb.ReadDwgFile(blockTemplate, System.IO.FileShare.Read, true, null);

                foreach (KeyValuePair <string, List <string> > d in data)
                {
                    string        file   = d.Key;
                    List <string> blocks = d.Value;

                    if (File.Exists(file))
                    {
                        ed.WriteMessage($"Open {file} to insert blocks.....\n");
                        try
                        {
                            Database db = new Database(false, true);
                            using (db)
                            {
                                //open drawing database
                                db.ReadDwgFile(file, System.IO.FileShare.ReadWrite, true, null);

                                #region load blocks into drawings, make sure the block is available to be inserted
                                List <string> loadedBlock = new List <string>();
                                try
                                {
                                    //create a variable to store the list of block identifiers
                                    ObjectIdCollection blockIdsToCopied = new ObjectIdCollection();
                                    Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager;
                                    using (Transaction tr = tm.StartTransaction())
                                    {
                                        ed.WriteMessage($"start transaction to copy blocks.....\n");
                                        BlockTable bt = tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false) as BlockTable;//open the block table
                                        //check each block in the block table
                                        foreach (ObjectId btrId in bt)
                                        {
                                            BlockTableRecord btr = tm.GetObject(btrId, OpenMode.ForRead, false) as BlockTableRecord;

                                            if (!btr.IsAnonymous && !btr.IsLayout)
                                            {
                                                blockIdsToCopied.Add(btrId);
                                                loadedBlock.Add(btr.Name);
                                                ed.WriteMessage($"Block: {btr.Name}, will be loaded in {file}.\n");
                                            }
                                            btr.Dispose();
                                        }
                                    }

                                    //copy blocks from source to destination database
                                    if (blockIdsToCopied.Count > 0)
                                    {
                                        IdMapping mapping = new IdMapping();
                                        sourceDb.WblockCloneObjects(blockIdsToCopied, db.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
                                        ed.WriteMessage($"copied blocks into {file}.....\n");
                                    }
                                }
                                catch { }
                                #endregion

                                #region determine what blocks needs to be added
                                //create the list of blocks that will be added
                                List <string> blocksTobeAdded = new List <string>();
                                foreach (string b in blockRequired)
                                {
                                    if (!blocks.Contains(b))
                                    {
                                        blocksTobeAdded.Add(b);
                                    }
                                }
                                #endregion

                                #region insert blocks into paper space
                                Point3d insPoint = new Point3d(0, 0, 0);
                                //string layoutName = "Layout1";//get all layout name
                                LayoutManager lm = LayoutManager.Current;
                                using (Transaction tr = db.TransactionManager.StartTransaction())
                                {
                                    BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                                    DBDictionary layoutDic = tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead, false) as DBDictionary;//get layout dictionary from current drawings
                                    foreach (DBDictionaryEntry entry in layoutDic)
                                    {
                                        ObjectId layoutId = entry.Value;                                        //layout id
                                        Layout   layout   = tr.GetObject(layoutId, OpenMode.ForRead) as Layout; //get layout
                                        if (layout.LayoutName == "Model")
                                        {
                                            continue;
                                        }

                                        BlockTableRecord btr = tr.GetObject(layout.BlockTableRecordId, OpenMode.ForWrite) as BlockTableRecord;
                                        foreach (string blockName in blocksTobeAdded)
                                        {
                                            ObjectId blkId = bt[blockName];
                                            ed.WriteMessage($"ObjectId {blkId} in {layout.LayoutName}\n");

                                            //insert the block
                                            BlockReference blkRef = new BlockReference(insPoint, blkId);
                                            btr.UpgradeOpen();
                                            btr.AppendEntity(blkRef);
                                            tr.AddNewlyCreatedDBObject(blkRef, true);

                                            ed.WriteMessage($"Insert {blockName} in {layout.LayoutName}\n");
                                        }
                                    }

                                    tr.Commit();
                                }
                                //foreach (string blockName in blocksTobeAdded)
                                //{
                                //    try
                                //    {
                                //        CADops.InsertBlock(db, layoutName, blockName, insPoint);
                                //        ed.WriteMessage($"Insert {blockName} in {file}\n");
                                //    }
                                //    catch { }
                                //}
                                #endregion
                                db.SaveAs(file, DwgVersion.Current);//save changes
                            }
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception ex)
                        { ed.WriteMessage(ex.ToString() + Environment.NewLine); }
                    }
                    else
                    {
                        ed.WriteMessage("File " + file + " does not exist.\n");
                    }
                }

                sourceDb.Dispose();
            }
            ed.WriteMessage($"Done.");
        }
コード例 #30
0
        // Thêm 1 block chứa bản vẽ của 1 file dwg vào bản vẽ hiện tại (có scale riêng)
        public static bool InsertDrawing(string partDwg, Scale3d scale, Point3d ipt, double angle, out ObjectId objectId)
        {
            Document doc       = AcAp.DocumentManager.MdiActiveDocument;
            Database curdb     = doc.Database; // Biến database của bản vẽ hện tại
            Editor   ed        = doc.Editor;
            string   blockname = Path.GetFileNameWithoutExtension(partDwg);
            bool     result    = false;

            objectId = ObjectId.Null;

            using (DocumentLock loc = doc.LockDocument())
            {
                ObjectId blkid = ObjectId.Null; // Biến lấy ID của file đọc vào
                try
                {
                    using (Database db = new Database(false, true))                  // Biến lấy database của file nạp vào
                    {
                        db.ReadDwgFile(partDwg, System.IO.FileShare.Read, true, ""); // Lấy database
                        blkid = curdb.Insert(partDwg, db, true);                     // Lấy ID
                    }
                }
                catch (IOException)
                {
                    return(false);
                }

                using (Transaction tr = doc.TransactionManager.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tr.GetObject(curdb.BlockTableId, OpenMode.ForRead);
                    if (!bt.Has(blockname))
                    {
                        bt.UpgradeOpen();
                        BlockTableRecord btrec = blkid.GetObject(OpenMode.ForRead) as BlockTableRecord;
                        btrec.UpgradeOpen();    //nâng cấp để ghi
                        btrec.Name = blockname; //thêm tên
                        btrec.DowngradeOpen();  //hạ cấp, không cho ghi nữa
                        bt.DowngradeOpen();
                    }
                    blkid = bt[blockname];

                    //Thêm các hình vẽ ở bản vẽ cũ vào
                    using (BlockTableRecord btr = (BlockTableRecord)curdb.CurrentSpaceId.GetObject(OpenMode.ForWrite))
                    {
                        //Insert vật thể
                        using (BlockReference bref = new BlockReference(ipt, blkid))
                        {
                            Matrix3d mat = Matrix3d.Identity;
                            bref.TransformBy(mat);
                            bref.ScaleFactors = scale;
                            bref.Rotation     = angle;
                            btr.AppendEntity(bref);
                            tr.AddNewlyCreatedDBObject(bref, true);
                            bref.DowngradeOpen();
                            objectId = bref.ObjectId;
                        }
                    }

                    //Tạo lại bản vẽ???
                    ed.Regen();
                    tr.Commit();
                    result = true;
                }
            }

            return(result);
        }