コード例 #1
0
ファイル: TKFind_Frm.cs プロジェクト: 1833183060/autocad-dev
 private void ListBox2_SelectedIndexChanged(object sender, EventArgs e)
 {
     using (this.transactionManager_0.StartTransaction())
     {
         BlockTable     blockTable     = (BlockTable)this.transactionManager_0.GetObject(this.database_1.BlockTableId, 0, false);
         BlockReference blockReference = (BlockReference)this.transactionManager_0.GetObject(blockTable[this.ListBox1.SelectedItem.ToString()], 0);
         blockTable.Dispose();
         this.PictureBox1.Image = this.ImageList1.Images[this.ListBox1.SelectedIndex];
     }
 }
コード例 #2
0
        public void ImportBlocks()
        {
            AcadApp.DocumentCollection dm = AcadApp.Application.DocumentManager;
            Editor       ed       = dm.MdiActiveDocument.Editor;
            Database     destDb   = dm.MdiActiveDocument.Database;
            Database     sourceDb = new Database(false, true);
            PromptResult sourceFileName;

            try
            {
                //从命令行要求用户输入以得到要导入的块所在的源DWG文件的名字
                sourceFileName = ed.GetString("\nEnter the name of the source drawing: ");
                //把源DWG读入辅助数据库
                sourceDb.ReadDwgFile(sourceFileName.StringResult, System.IO.FileShare.Write, true, "");
                //用集合变量来存储块ID的列表
                ObjectIdCollection blockIds = new ObjectIdCollection();
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm =
                    sourceDb.TransactionManager;
                using (Transaction myT = tm.StartTransaction())
                {
                    //打开块表
                    BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId,
                                                             OpenMode.ForRead, false);
                    //在块表中检查每个块
                    foreach (ObjectId btrId in bt)
                    {
                        BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId,
                                                                              OpenMode.ForRead, false);
                        //只添加有名块和非layout块(layout块是非MS和非PS的块)
                        if (!btr.IsAnonymous && !btr.IsLayout)
                        {
                            blockIds.Add(btrId);
                        }
                        btr.Dispose(); //释放块表记录引用变量所占用的资源
                    }
                    bt.Dispose();      //释放块表引用变量所占用的资源
                    //没有作改变,不需要提交事务
                    myT.Dispose();
                }

                IdMapping mapping = new IdMapping();
                mapping = sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, DuplicateRecordCloning.Replace, false);

                ed.WriteMessage("\nCopied " + blockIds.Count.ToString() + " block definitions from " + sourceFileName.StringResult + " to the current drawing.");
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\nError during copy: " + ex.Message);
            }
            sourceDb.Dispose();
        }
コード例 #3
0
ファイル: Macros.cs プロジェクト: kojtoLtd/KojtoCAD
        public void ReplaceBlockWithFileStart()
        {
            Application.SetSystemVariable("FILEDIA", 1);
            var editorUtility = new EditorHelper(Application.DocumentManager.MdiActiveDocument);
            PromptEntityResult blockToReplaceResult = editorUtility.PromptForObject("Select the block to replace : ",
                                                                                    typeof(BlockReference), false);

            if (blockToReplaceResult.Status != PromptStatus.OK)
            {
                return;
            }

            var openFileDialog = new System.Windows.Forms.OpenFileDialog();

            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            if (!File.Exists(openFileDialog.FileName))
            {
                _ed.WriteMessage("File does not exists.");
                return;
            }

            if (!openFileDialog.FileName.EndsWith(".dwg", StringComparison.InvariantCultureIgnoreCase))
            {
                _ed.WriteMessage("File is not a DWG.");
                return;
            }

            Point3d selectedEntityPoint;

            using (Transaction transaction = _db.TransactionManager.StartTransaction())
            {
                BlockTable blockTable     = (BlockTable)transaction.GetObject(_db.BlockTableId, OpenMode.ForWrite);
                Entity     selectedEntity = (Entity)transaction.GetObject(blockToReplaceResult.ObjectId, OpenMode.ForWrite);

                selectedEntityPoint = ((BlockReference)selectedEntity).Position;
                selectedEntity.Erase();

                blockTable.DowngradeOpen();
                blockTable.Dispose();

                transaction.Commit();
            }

            ReplaceBlockRefWithDWG(_doc, openFileDialog.FileName, selectedEntityPoint, _ed.CurrentUserCoordinateSystem);
            _logger.Info(MethodBase.GetCurrentMethod().Name);
        }
コード例 #4
0
        public void ImportBlocksFromDwg(string sourceFileName)
        {
            DocumentCollection dm = Application.DocumentManager;
            Editor             ed = dm.MdiActiveDocument.Editor;
            //获取当前数据库作为目标数据库
            Database destDb = dm.MdiActiveDocument.Database;
            //创建一个新的数据库对象,作为源数据库,以读入外部文件中的对象
            Database sourceDb = new Database(false, true);

            try
            {
                //把DWG文件读入到一个临时的数据库中
                sourceDb.ReadDwgFile(sourceFileName, System.IO.FileShare.Read, true, null);
                //创建一个变量用来存储块的ObjectId列表
                ObjectIdCollection blockIds = new ObjectIdCollection();
                //获取源数据库的事务处理管理器
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager;
                //在源数据库中开始事务处理
                using (Transaction myT = tm.StartTransaction())
                {
                    //打开源数据库中的块表
                    BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false);
                    //遍历每个块
                    foreach (ObjectId btrId in bt)
                    {
                        BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false);
                        //只加入命名块和非布局块到复制列表中
                        if (!btr.IsAnonymous && !btr.IsLayout)
                        {
                            blockIds.Add(btrId);
                        }
                        btr.Dispose();
                    }
                    bt.Dispose();
                }
                //定义一个IdMapping对象
                IdMapping mapping = new IdMapping();
                //从源数据库向目标数据库复制块表记录
                sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
                //'复制完成后,命令行显示复制了多少个块的信息
                ed.WriteMessage("复制了 " + blockIds.Count.ToString() + " 个块,从 " + sourceFileName + " 到当前图形");
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\nError during copy: " + ex.Message);
            }
            //操作完成,销毁源数据库
            sourceDb.Dispose();
        }
コード例 #5
0
        /// <summary>
        /// 导入外部文件中的块
        /// </summary>
        /// <param name="destDb">目标数据库</param>
        /// <param name="sourceFileName">包含完整路径的外部文件名</param>
        public static void ImportBlocksFromDwg(this Database destDb, string sourceFileName)
        {
            //创建一个新的数据库对象,作为源数据库,以读入外部文件中的对象
            Database sourceDb = new Database(false, true);

            try
            {
                //把DWG文件读入到一个临时的数据库中
                sourceDb.ReadDwgFile(sourceFileName, System.IO.FileShare.Read, true, null);
                //创建一个变量用来存储块的ObjectId列表
                ObjectIdCollection blockIds = new ObjectIdCollection();
                //获取源数据库的事务处理管理器
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = sourceDb.TransactionManager;
                //在源数据库中开始事务处理
                using (Transaction myT = tm.StartTransaction())
                {
                    //打开源数据库中的块表
                    BlockTable bt = (BlockTable)tm.GetObject(sourceDb.BlockTableId, OpenMode.ForRead, false);
                    //遍历每个块
                    foreach (ObjectId btrId in bt)
                    {
                        BlockTableRecord btr = (BlockTableRecord)tm.GetObject(btrId, OpenMode.ForRead, false);
                        //只加入命名块和非布局块到复制列表中
                        if (!btr.IsAnonymous && !btr.IsLayout)
                        {
                            blockIds.Add(btrId);
                        }
                        btr.Dispose();
                    }
                    bt.Dispose();
                }
                //定义一个IdMapping对象
                IdMapping mapping = new IdMapping();
                //从源数据库向目标数据库复制块表记录
                sourceDb.WblockCloneObjects(blockIds, destDb.BlockTableId, mapping, DuplicateRecordCloning.Replace, false);
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                Application.ShowAlertDialog("复制错误: " + ex.Message);
            }
            //操作完成,销毁源数据库
            sourceDb.Dispose();
        }
コード例 #6
0
ファイル: TKFind_Frm.cs プロジェクト: 1833183060/autocad-dev
 private void TKFind_Frm_Load(object sender, EventArgs e)
 {
     Interaction.MsgBox(this.string_0, MsgBoxStyle.OkOnly, null);
     this.database_1 = new Database(false, true);
     this.database_1.ReadDwgFile(this.string_0, FileShare.Read, true, "");
     this.transactionManager_0 = this.database_1.TransactionManager;
     checked
     {
         using (this.transactionManager_0.StartTransaction())
         {
             BlockTable blockTable = (BlockTable)this.transactionManager_0.GetObject(this.database_1.BlockTableId, 0, false);
             try
             {
                 foreach (ObjectId objectId in blockTable)
                 {
                     BlockTableRecord blockTableRecord = (BlockTableRecord)this.transactionManager_0.GetObject(objectId, 0, false);
                     if (blockTableRecord.Name.ToString().Length >= 3 && Operators.CompareString(blockTableRecord.Name.ToString().Substring(0, 3), "TC_", false) == 0)
                     {
                         Interaction.MsgBox(blockTableRecord.PreviewIcon.Width, MsgBoxStyle.OkOnly, null);
                         int num;
                         this.ListBox1.Items.Add(blockTableRecord.Name.ToString() + "@" + Conversions.ToString(num));
                         num++;
                     }
                 }
             }
             finally
             {
                 SymbolTableEnumerator enumerator;
                 if (enumerator != null)
                 {
                     enumerator.Dispose();
                 }
             }
             blockTable.Dispose();
         }
         Interaction.MsgBox(Information.Err().Description, MsgBoxStyle.OkOnly, null);
     }
 }
コード例 #7
0
        public ObjectId BlockDefinitionToNativeDB(BlockDefinition definition)
        {
            // get modified definition name with commit info
            var blockName = RemoveInvalidAutocadChars($"{Doc.UserData["commit"]} - {definition.name}");

            ObjectId blockId = ObjectId.Null;

            // see if block record already exists and return if so
            BlockTable blckTbl = Trans.GetObject(Doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable;

            if (blckTbl.Has(blockName))
            {
                return(blckTbl[blockName]);
            }

            // create btr
            using (BlockTableRecord btr = new BlockTableRecord())
            {
                btr.Name = blockName;

                // base point
                btr.Origin = PointToNative(definition.basePoint);

                // add geometry
                blckTbl.UpgradeOpen();
                var bakedGeometry = new ObjectIdCollection(); // this is to contain block def geometry that is already added to doc space during conversion
                foreach (var geo in definition.geometry)
                {
                    if (CanConvertToNative(geo))
                    {
                        Entity converted = null;
                        switch (geo)
                        {
                        case BlockInstance o:
                            BlockInstanceToNativeDB(o, out BlockReference reference, false);
                            converted = reference;
                            break;

                        default:
                            converted = ConvertToNative(geo) as Entity;
                            break;
                        }

                        if (converted == null)
                        {
                            continue;
                        }
                        else if (!converted.IsNewObject && !(converted is BlockReference))
                        {
                            bakedGeometry.Add(converted.Id);
                        }
                        else
                        {
                            btr.AppendEntity(converted);
                        }
                    }
                }
                blockId = blckTbl.Add(btr);
                btr.AssumeOwnershipOf(bakedGeometry); // add in baked geo
                Trans.AddNewlyCreatedDBObject(btr, true);
                blckTbl.Dispose();
            }


            return(blockId);
        }
コード例 #8
0
ファイル: Form1.cs プロジェクト: mzh3511/OdExamplesMgd
        private void file_open_handler(object sender, EventArgs e)
        {
            if (DialogResult.OK == openFileDialog.ShowDialog(this))
            {
                if (lm != null)
                {
                    lm.LayoutSwitched -= new Teigha.DatabaseServices.LayoutEventHandler(reinitGraphDevice);
                    HostApplicationServices.WorkingDatabase = null;
                    lm = null;
                }

                bool bLoaded = true;
                database = new Database(false, false);
                if (openFileDialog.FilterIndex == 1)
                {
                    try
                    {
                        database.ReadDwgFile(openFileDialog.FileName, FileOpenMode.OpenForReadAndAllShare, false, "");



                        //现在进入数据库并获得数据库的块表引用
                        Transaction trans = database.TransactionManager.StartTransaction();
                        BlockTable  bt    = (BlockTable)trans.GetObject(database.BlockTableId, OpenMode.ForRead, false, true);
                        //从块表的模型空间特性中获得块表记录,块表记录对象包含DWG文件数据库实体
                        BlockTableRecord btr = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead, false, true);
                        foreach (ObjectId btrId in btr)
                        {
                            DBObject entBlock = (DBObject)trans.GetObject(btrId, OpenMode.ForRead, false, true);
                            String   dxfName  = entBlock.GetRXClass().DxfName;
                            if (entBlock.GetRXClass().DxfName.ToUpper() == "INSERT")
                            {
                                BlockReference bRef = (BlockReference)entBlock;
                                if (bRef.AttributeCollection.Count != 0)
                                {
                                    System.Collections.IEnumerator bRefEnum = bRef.AttributeCollection.GetEnumerator();
                                    while (bRefEnum.MoveNext())
                                    {
                                        ObjectId           aId  = (ObjectId)bRefEnum.Current;//这一句极其关键
                                        AttributeReference aRef = (AttributeReference)trans.GetObject(aId, OpenMode.ForRead, false, true);
                                        string             sss  = aRef.TextString;
                                        //this.textBox1.Text = aRef.TextString;//此语句即获得属性单行文本,请自行在此语句前添加 属性单行文本 赋于的变量
                                    }
                                }
                            }
                            if (entBlock.GetRXClass().DxfName.ToUpper() == "MTEXT")
                            {
                                MText  bRef = (MText)entBlock;
                                string sd   = bRef.Text;
                            }
                            if (entBlock.GetRXClass().DxfName.ToUpper() == "LINE")
                            {
                                Line     bRef = (Line)entBlock;
                                ObjectId oid  = bRef.Id;
                            }
                        }
                        trans.Commit(); //提交事务处理
                        btr.Dispose();
                        bt.Dispose();
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        bLoaded = false;
                    }
                }
                else if (openFileDialog.FilterIndex == 2)
                {
                    try
                    {
                        database.DxfIn(openFileDialog.FileName, "");
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        bLoaded = false;
                    }
                }

                if (bLoaded)
                {
                    HostApplicationServices.WorkingDatabase = database;
                    lm = LayoutManager.Current;
                    lm.LayoutSwitched += new Teigha.DatabaseServices.LayoutEventHandler(reinitGraphDevice);
                    String str = HostApplicationServices.Current.FontMapFileName;

                    //menuStrip.
                    exportToolStripMenuItem.Enabled          = true;
                    zoomToExtentsToolStripMenuItem.Enabled   = true;
                    zoomWindowToolStripMenuItem.Enabled      = true;
                    setAvtiveLayoutToolStripMenuItem.Enabled = true;
                    fileDependencyToolStripMenuItem.Enabled  = true;
                    panel1.Enabled = true;
                    pageSetupToolStripMenuItem.Enabled    = true;
                    printPreviewToolStripMenuItem.Enabled = true;
                    printToolStripMenuItem.Enabled        = true;
                    this.Text = String.Format("OdViewExMgd - [{0}]", openFileDialog.SafeFileName);

                    initializeGraphics();
                    Invalidate();
                }
            }
        }
コード例 #9
0
        // List info about all text objects in current (open) dwg and print info to XAML text box
        public List <String> Process()
        {
            List <String> TextList = new List <String>();

            try
            {
                // Putting this in a using statement messes up the dwg instance for the ed.writemesssage() in finally {} of entrycmdclass.cs
                Document currentDoc = Application.DocumentManager.MdiActiveDocument;
                _Path = currentDoc.Database.Filename;
                //Database oldDb = Autodesk.AutoCAD.DatabaseServices.HostApplicationServices.WorkingDatabase;

                using (Database db = currentDoc.Database)
                {
                    using (Transaction acTrans = db.TransactionManager.StartTransaction())
                    {
                        // Dont use polymorphic ToEach way because here we want text objects from ALL blocks, not just model space
                        //IList<DBText> textObjs = ToEach.toEach<DBText>(db, acTrans, (s) => true);

                        //foreach (DBText dbt in textObjs)
                        //{
                        BlockTable bt = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                        foreach (ObjectId btrId in bt)
                        {
                            BlockTableRecord btr = acTrans.GetObject(btrId, OpenMode.ForRead) as BlockTableRecord;

                            foreach (ObjectId entId in btr)
                            {
                                if (entId.ObjectClass.DxfName == "TEXT")
                                {
                                    using (DBText dbt = acTrans.GetObject(entId, OpenMode.ForRead) as DBText)
                                    {
                                        StringBuilder currentString = new StringBuilder();
                                        // Print the block, layer, text value, and truncated x,y values
                                        currentString.Append(dbt.BlockName)
                                        .Append("   :   ")
                                        .Append(dbt.Layer)
                                        .Append("   :   ")
                                        .Append(String.Concat("(", dbt.Position.X.truncstring(2), ", ", dbt.Position.Y.truncstring(2), ")"))
                                        .Append("   :   ")
                                        .Append(dbt.TextString);

                                        TextList.Add(currentString.ToString());
                                    }
                                }
                            }
                            if (!btr.IsDisposed)
                            {
                                btr.Dispose();
                            }
                        }
                        if (!bt.IsDisposed)
                        {
                            bt.Dispose();
                        }
                        //}
                        acTrans.Commit();
                    }
                }
                return((TextList.Count == 0) ? (new List <String>()
                {
                    "No text found."
                }) : TextList.OrderBy <String, String>((s) => s).ToList());
            }
            catch
            {
                throw; //   return String.Concat("Error: ", se.Message);
            }
        }