CAD插件实现:所有文字显示到列表、缩放、编辑——CAD-c#二次开发

当图中有大量文字,需要全部显示到一个列表时并缩放到需要的文字时,可采用插件实现,效果如下:

CAD插件实现:所有文字显示到列表、缩放、编辑——CAD-c#二次开发_第1张图片

附部分代码如下:

 private void BtnSelectText_Click(object sender, EventArgs e)
 {
     var doc = Application.DocumentManager.MdiActiveDocument;
     var db = doc.Database;
     var ed = doc.Editor;

     // 激活CAD窗口(修复问题1)
     Autodesk.AutoCAD.ApplicationServices.Application.MainWindow.Focus();

     // 创建选择过滤器(新增批量选择功能)
     var filter = new SelectionFilter(
         new[]
         {
          new TypedValue((int)DxfCode.Operator, "") // 结束逻辑或
         });

     var options = new PromptSelectionOptions
     {
         MessageForAdding = "\n选择要添加的文字: ",
         AllowDuplicates = false
     };

     try
     {
         // 执行批量选择(替换原来的GetEntity)
         var result = ed.GetSelection(options, filter);

         if (result.Status != PromptStatus.OK) return;
         // 获取选中的ObjectId并去重
         var selectedIds = new HashSet(result.Value.GetObjectIds());
         // 获取现有表格中的ObjectId
         var existingIds = new HashSet();
         dataGridView.Invoke((MethodInvoker)delegate
         {
             foreach (DataGridViewRow row in dataGridView.Rows)
             {
                 if (row.Tag is ObjectId id)
                 {
                     existingIds.Add(id);
                 }
             }
         });
         // 计算需要添加的新ID
         var newIds = selectedIds.Except(existingIds).ToList();
         if (newIds.Count == 0)
         {
             ed.WriteMessage("\n没有新文字需要添加!\n");
             return;
         }
         using (Transaction tr = db.TransactionManager.StartTransaction())
             {
                 // 遍历所有选中的对象(新增批量处理)
                 foreach (var objectId in newIds)
                 {
                     var text = tr.GetObject(objectId, OpenMode.ForRead) as Entity;

                     string content = "";
                     string color = "";

                     if (text is DBText dbText)
                     {
                         content = dbText.TextString;
                         color = dbText.Color.ToString();
                     }
                     else if (text is MText mText)
                     {
                         content = mText.Contents; // 修正MText内容获取方式
                         color = mText.Color.ToString();
                     }

                     // 跨线程更新UI(重要!)
                     dataGridView.Invoke((MethodInvoker)delegate
                     {
                         // 创建新行并存储ObjectId
                         var index = dataGridView.Rows.Add(content, color);
                         dataGridView.Rows[index].Tag = objectId; // 关键修改:存储对象ID
                     });
                 }
                 tr.Commit();
             }
     }
     catch (System.Exception ex)
     {
         ed.WriteMessage($"\n选择错误: {ex.Message}");
     }
 }

插件联系(可另行定制功能)↓ ↓ ↓ 

你可能感兴趣的:(WPF入门(C#),CAD,C#二次开发,c#,数据库,开发语言)