找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 759|回复: 2

[每日一码] 隐藏、孤立、反向可见等实现的代码

[复制链接]

已领礼包: 20个

财富等级: 恭喜发财

发表于 2021-1-20 04:40:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
提供了四个命令:

HIDENT:隐藏所选对象
ISOLENT:隔离选定的对象(隐藏所有其他对象)
INVIZ:反转对象可见性
UNISOLENT:取消隐藏所有对象

这些命令被添加到默认上下文菜单中,而HIDENT和ISOLENT也被添加到对象上下文菜单中。
由于Visible属性仅以编程方式可用,因此出现一个消息框,要求用户在保存时取消隐藏隐藏的对象(如果有)。 相同的消息警告用户打开新图形。
提示在法语AutoCAD版本上以法语显示,否则以英语显示。


  1. using System;
  2. using Autodesk.AutoCAD.ApplicationServices;
  3. using Autodesk.AutoCAD.DatabaseServices;
  4. using Autodesk.AutoCAD.EditorInput;
  5. using Autodesk.AutoCAD.Runtime;
  6. using Autodesk.AutoCAD.Windows;
  7. using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;

  8. [assembly: ExtensionApplication(typeof(IsolateObjects.Commands))]

  9. namespace IsolateObjects
  10. {
  11.     public class Commands : IExtensionApplication
  12.     {
  13.         private bool fra = (string)acadApp.GetSystemVariable("LOCALE") == "FRA";
  14.         private DocumentCollection docMan = acadApp.DocumentManager;

  15.         // Abonnement à l'évènement "DocumentCreated"
  16.         // Abonnement de tous les documents ouverts à l'évènement "BeginSave"
  17.         // Ajouts aux menus contextuel
  18.         public void Initialize()
  19.         {
  20.             docMan.DocumentCreated += new DocumentCollectionEventHandler(OnDocumentCreated);
  21.             foreach (Document doc in docMan)
  22.             {
  23.                 doc.Database.BeginSave += new DatabaseIOEventHandler(OnSaveAlert);
  24.             }
  25.             ContextMenu.AddDefaultContextMenu();
  26.             ContextMenu.AddObjectContextMenu();
  27.             ShowMessage();
  28.         }

  29.         // Suppression des ajouts aux menus contextuels
  30.         public void Terminate()
  31.         {
  32.             ContextMenu.RemoveDefaultContextMenu();
  33.             ContextMenu.RemoveObjectContextMenu();
  34.         }

  35.         // Réaction à l'ouverture d'un document => abonnement à l'évènement "BeginSave"
  36.         private void OnDocumentCreated(object sender, DocumentCollectionEventArgs e)
  37.         {
  38.             e.Document.Database.BeginSave += new DatabaseIOEventHandler(OnSaveAlert);
  39.             ShowMessage();
  40.         }

  41.         // Réaction à l'évènement "Database.BeginSave"
  42.         private void OnSaveAlert(object sender, DatabaseIOEventArgs e)
  43.         {
  44.             ShowMessage();
  45.         }

  46.         // MessageBox
  47.         private void ShowMessage()
  48.         {
  49.             int num = Dictionary.GetHiddenNumber();
  50.             if (num != 0)
  51.             {
  52.                 System.Windows.Forms.DialogResult dr =
  53.                     System.Windows.Forms.MessageBox.Show(
  54.                     num.ToString() + (fra ?
  55.                     " objets invisibles\nRestaurer la visibilite ?" :
  56.                     " invisible objects\nRestore visibility ?"),
  57.                     fra ? "Visibilité des entités" : "Objects visibility",
  58.                     System.Windows.Forms.MessageBoxButtons.YesNo,
  59.                     System.Windows.Forms.MessageBoxIcon.Question);
  60.                 if (dr == System.Windows.Forms.DialogResult.Yes)
  61.                     UnisolateObjects();
  62.             }
  63.         }

  64.         // Commande HIDENT : rendre invisibles les entités sélectionnées
  65.         [CommandMethod("HIDENT", CommandFlags.Modal | CommandFlags.UsePickSet)]
  66.         public void HideObjects()
  67.         {
  68.             Document doc = docMan.MdiActiveDocument;
  69.             Database db = doc.Database;
  70.             Editor ed = doc.Editor;
  71.             PromptSelectionOptions pso = new PromptSelectionOptions();
  72.             pso.MessageForAdding = fra ? "Sélectionnez les objets à cacher: " : "\nSelect objects to hide: ";
  73.             PromptSelectionResult psr = ed.GetSelection(pso);
  74.             if (psr.Status == PromptStatus.OK)
  75.             {
  76.                 try
  77.                 {
  78.                     int cnt = 0;
  79.                     ObjectId[] selSet = psr.Value.GetObjectIds();
  80.                     using (Transaction tr = db.TransactionManager.StartTransaction())
  81.                     {
  82.                         foreach (ObjectId id in selSet)
  83.                         {
  84.                             Entity ent = (Entity)tr.GetObject(id, OpenMode.ForWrite, false, true);
  85.                             ent.Visible = false;
  86.                             cnt++;
  87.                         }
  88.                         tr.Commit();
  89.                     }
  90.                     ed.WriteMessage(
  91.                         "\n{0} {1} (total : {2})",
  92.                         cnt.ToString(),
  93.                         fra ? "entités rendues invisibles" : "objects have been hidden",
  94.                         Dictionary.SetHiddenNumber(cnt).ToString());
  95.                 }
  96.                 catch (System.Exception ex)
  97.                 {
  98.                     ed.WriteMessage((fra ? "\nErreur: " : "\nError: ") + ex.Message);
  99.                 }
  100.             }
  101.         }

  102.         // Commande ISOLENT : isoler les entités sélectionnées (rendre invisibles les autres)
  103.         [CommandMethod("ISOLENT", CommandFlags.Modal | CommandFlags.UsePickSet)]
  104.         public void IsolateObjects()
  105.         {
  106.             Document doc = docMan.MdiActiveDocument;
  107.             Database db = doc.Database;
  108.             Editor ed = doc.Editor;
  109.             PromptSelectionOptions pso = new PromptSelectionOptions();
  110.             pso.MessageForAdding = fra ? "Sélectionnez les objets à isoler: " : "\nSelect objects to isolate";
  111.             PromptSelectionResult psr = ed.GetSelection(pso);
  112.             if (psr.Status == PromptStatus.OK)
  113.             {
  114.                 try
  115.                 {
  116.                     int cnt = 0;
  117.                     ObjectId[] selSet = psr.Value.GetObjectIds();
  118.                     using (Transaction tr = db.TransactionManager.StartTransaction())
  119.                     {
  120.                         BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
  121.                         BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
  122.                         foreach (ObjectId id in btr)
  123.                         {
  124.                             Entity ent = tr.GetObject(id, OpenMode.ForWrite, false, true) as Entity;
  125.                             if (ent != null)
  126.                             {
  127.                                 ent.Visible = false;
  128.                                 cnt++;
  129.                             }
  130.                         }
  131.                         foreach (ObjectId id in selSet)
  132.                         {
  133.                             Entity ent = tr.GetObject(id, OpenMode.ForWrite, false, true) as Entity;
  134.                             ent.Visible = true;
  135.                             cnt--;
  136.                         }
  137.                         tr.Commit();
  138.                     }
  139.                     ed.WriteMessage(
  140.                         "\n{0} {1} (total : {2})",
  141.                         cnt.ToString(),
  142.                         fra ? "entités rendues invisibles" : "objects have been hidden",
  143.                         Dictionary.SetHiddenNumber(cnt).ToString());
  144.                 }
  145.                 catch (System.Exception ex)
  146.                 {
  147.                     ed.WriteMessage((fra ? "\nErreur: " : "\nError: ") + ex.Message);
  148.                 }
  149.             }
  150.         }

  151.         // Commande : UNISOLENT : rendre visibles toutes les entités
  152.         [CommandMethod("UNISOLENT")]
  153.         public void UnisolateObjects()
  154.         {
  155.             Document doc = docMan.MdiActiveDocument;
  156.             Database db = doc.Database;
  157.             Editor ed = doc.Editor;
  158.             try
  159.             {
  160.                 int cnt = 0;
  161.                 using (Transaction tr = db.TransactionManager.StartTransaction())
  162.                 {
  163.                     BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
  164.                     BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
  165.                     foreach (ObjectId id in btr)
  166.                     {
  167.                         Entity ent = tr.GetObject(id, OpenMode.ForWrite, false, true) as Entity;
  168.                         if ((ent != null) && (ent.Visible == false))
  169.                         {
  170.                             ent.Visible = true;
  171.                             cnt++;
  172.                         }
  173.                     }
  174.                     Dictionary.Erase();
  175.                     tr.Commit();
  176.                 }
  177.                 ed.WriteMessage(
  178.                     "\n{0} {1}",
  179.                     cnt.ToString(),
  180.                     fra ? "entités rendues visibles" : "objects have been unhidden");
  181.             }
  182.             catch (System.Exception ex)
  183.             {
  184.                 ed.WriteMessage((fra ? "\nErreur: " : "\nError: ") + ex.Message);
  185.             }
  186.         }

  187.         // Commande INVIZ : inverser la visibilité des entités
  188.         [CommandMethod("INVIZ")]
  189.         public void InverseVisibility()
  190.         {
  191.             Document doc = docMan.MdiActiveDocument;
  192.             Database db = doc.Database;
  193.             Editor ed = doc.Editor;
  194.             try
  195.             {
  196.                 int cnt1 = 0, cnt2 = 0;
  197.                 using (Transaction tr = db.TransactionManager.StartTransaction())
  198.                 {
  199.                     BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
  200.                     BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
  201.                     foreach (ObjectId id in btr)
  202.                     {
  203.                         Entity ent = tr.GetObject(id, OpenMode.ForWrite, false, true) as Entity;
  204.                         if (ent != null)
  205.                         {
  206.                             if (ent.Visible == true)
  207.                             {
  208.                                 ent.Visible = false;
  209.                                 cnt1++;
  210.                             }
  211.                             else
  212.                             {
  213.                                 ent.Visible = true;
  214.                                 cnt2++;
  215.                             }
  216.                         }
  217.                     }
  218.                     tr.Commit();
  219.                 }
  220.                 Dictionary.SetHiddenNumber(cnt1 - cnt2);
  221.                 ed.WriteMessage(
  222.                     "\n{0} {1} {2} {3})",
  223.                     cnt2.ToString(),
  224.                     fra ? "entités rendues visibles," : "objects have been unhidden,",
  225.                     cnt1.ToString(),
  226.                     fra ? "rendues invisibles" : "have been hidden");
  227.             }
  228.             catch (System.Exception ex)
  229.             {
  230.                 ed.WriteMessage((fra ? "\nErreur: " : "\nError: ") + ex.Message);
  231.             }
  232.         }
  233.     }

  234.     public class ContextMenu
  235.     {
  236.         private static ContextMenuExtension ocme, dcme;
  237.         private static bool fra = (string)acadApp.GetSystemVariable("LOCALE") == "FRA";

  238.         // Ajouts au menu contextuel objets
  239.         internal static void AddObjectContextMenu()
  240.         {
  241.             ocme = new ContextMenuExtension();
  242.             MenuItem hide = new MenuItem(fra ? "Cacher les objets" : "Hide objects");
  243.             MenuItem isolate = new MenuItem(fra ? "Isoler les objets" : "Isolate objects");
  244.             ocme.MenuItems.Add(hide);
  245.             ocme.MenuItems.Add(isolate);
  246.             hide.Click += new EventHandler(hide_Click);
  247.             isolate.Click += new EventHandler(isolate_Click);
  248.             RXClass rxc = Entity.GetClass(typeof(Entity));
  249.             acadApp.AddObjectContextMenuExtension(rxc, ocme);
  250.         }

  251.         // Ajouts au menu contextuel par défaut
  252.         internal static void AddDefaultContextMenu()
  253.         {
  254.             dcme = new ContextMenuExtension();
  255.             dcme.Title = (fra ? "Visibilité des objets" : "Objects visibility");
  256.             MenuItem hide = new MenuItem(fra ? "Cacher" : "Hide");
  257.             MenuItem isolate = new MenuItem(fra ? "Isoler" : "Isolate");
  258.             MenuItem inverse = new MenuItem(fra ? "Inverser" : "Toggle");
  259.             MenuItem unisolate = new MenuItem(fra ? "Afficher tout" : "Unhide all");
  260.             dcme.MenuItems.Add(hide);
  261.             dcme.MenuItems.Add(isolate);
  262.             dcme.MenuItems.Add(inverse);
  263.             dcme.MenuItems.Add(unisolate);
  264.             hide.Click += new EventHandler(hide_Click);
  265.             isolate.Click += new EventHandler(isolate_Click);
  266.             inverse.Click += new EventHandler(inverse_Click);
  267.             unisolate.Click += new EventHandler(unisolate_Click);
  268.             acadApp.AddDefaultContextMenuExtension(dcme);
  269.         }

  270.         // Suppression du menu contextuel par défaut
  271.         internal static void RemoveDefaultContextMenu()
  272.         {
  273.             acadApp.RemoveDefaultContextMenuExtension(dcme);
  274.         }

  275.         // Suppression du menu contextuel objets
  276.         internal static void RemoveObjectContextMenu()
  277.         {
  278.             RXClass rxc = Entity.GetClass(typeof(Entity));
  279.             acadApp.RemoveObjectContextMenuExtension(rxc, ocme);
  280.         }

  281.         // Réaction au clic sur "Afficher tout"
  282.         private static void unisolate_Click(object sender, EventArgs e)
  283.         {
  284.             Document doc = acadApp.DocumentManager.MdiActiveDocument;
  285.             doc.SendStringToExecute("UNISOLENT ", true, false, true);
  286.         }

  287.         // Réaction au clic sur "Inverser"
  288.         private static void inverse_Click(object sender, EventArgs e)
  289.         {
  290.             Document doc = acadApp.DocumentManager.MdiActiveDocument;
  291.             doc.SendStringToExecute("INVIZ ", true, false, true);
  292.         }

  293.         // Réaction au clic sur "Isoler"
  294.         private static void isolate_Click(object sender, EventArgs e)
  295.         {
  296.             Document doc = acadApp.DocumentManager.MdiActiveDocument;
  297.             doc.SendStringToExecute("ISOLENT ", true, false, true);
  298.         }

  299.         // Réaction au clic sur "Cacher"
  300.         private static void hide_Click(object sender, EventArgs e)
  301.         {
  302.             Document doc = acadApp.DocumentManager.MdiActiveDocument;
  303.             doc.SendStringToExecute("HIDENT ", true, false, true);
  304.         }
  305.     }

  306.     public class Dictionary
  307.     {
  308.         private const string kDict = "GILE_HIDENTS";
  309.         private const string kXrec = "HiddenEntitiesNumber";

  310.         // Ajout ou modification de l'entrée "HiddenEntitiesNumber" du dictionnaire "GILE_HIDENTS"
  311.         internal static int SetHiddenNumber(int num)
  312.         {
  313.             Database db = acadApp.DocumentManager.MdiActiveDocument.Database;
  314.             using (Transaction tr = db.TransactionManager.StartTransaction())
  315.             {
  316.                 DBDictionary NOD = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead);
  317.                 DBDictionary dict;
  318.                 Xrecord xrec;
  319.                 ResultBuffer data;
  320.                 if (NOD.Contains(kDict))
  321.                 {
  322.                     dict = (DBDictionary)tr.GetObject(NOD.GetAt(kDict), OpenMode.ForRead);
  323.                 }
  324.                 else
  325.                 {
  326.                     NOD.UpgradeOpen();
  327.                     dict = new DBDictionary();
  328.                     NOD.SetAt(kDict, dict);
  329.                     tr.AddNewlyCreatedDBObject(dict, true);
  330.                 }
  331.                 if (dict.Contains(kXrec))
  332.                 {
  333.                     xrec = (Xrecord)tr.GetObject(dict.GetAt(kXrec), OpenMode.ForWrite);
  334.                     data = xrec.Data;
  335.                     num += (int)(data.AsArray())[0].Value;
  336.                     TypedValue[] tva = { new TypedValue((int)DxfCode.Int32, num) };
  337.                     data = new ResultBuffer(tva);
  338.                 }
  339.                 else
  340.                 {
  341.                     dict.UpgradeOpen();
  342.                     xrec = new Xrecord();
  343.                     dict.SetAt(kXrec, xrec);
  344.                     tr.AddNewlyCreatedDBObject(xrec, true);
  345.                     TypedValue[] tva = { new TypedValue((int)DxfCode.Int32, num) };
  346.                     data = new ResultBuffer(tva);
  347.                 }
  348.                 xrec.Data = data;
  349.                 tr.Commit();
  350.             }
  351.             return num;
  352.         }

  353.         // Récupération la valeur de l'entrée "HiddenEntitiesNumber" du dictionnaire "GILE_HIDENTS"
  354.         internal static int GetHiddenNumber()
  355.         {
  356.             Database db = acadApp.DocumentManager.MdiActiveDocument.Database;
  357.             using (Transaction tr = db.TransactionManager.StartTransaction())
  358.             {
  359.                 DBDictionary NOD = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead);
  360.                 try
  361.                 {
  362.                     DBDictionary dict = (DBDictionary)tr.GetObject(NOD.GetAt(kDict), OpenMode.ForRead);
  363.                     Xrecord xrec = (Xrecord)tr.GetObject(dict.GetAt(kXrec), OpenMode.ForRead);
  364.                     ResultBuffer data = xrec.Data;
  365.                     return (int)(data.AsArray())[0].Value;
  366.                 }
  367.                 catch (System.Exception)
  368.                 {
  369.                     return 0;
  370.                 }
  371.             }
  372.         }

  373.         // Suppression du dictionnaire "GILE_HIDENTS"
  374.         internal static void Erase()
  375.         {
  376.             Database db = acadApp.DocumentManager.MdiActiveDocument.Database;
  377.             using (Transaction tr = db.TransactionManager.StartTransaction())
  378.             {
  379.                 DBDictionary NOD = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite);
  380.                 if (NOD.Contains(kDict))
  381.                 {
  382.                     DBDictionary dict = (DBDictionary)tr.GetObject(NOD.GetAt(kDict), OpenMode.ForWrite);
  383.                     dict.Erase(true);
  384.                 }
  385.                 tr.Commit();
  386.             }
  387.         }
  388.     }
  389. }
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!

已领礼包: 3904个

财富等级: 富可敌国

发表于 2021-1-20 08:28:35 | 显示全部楼层
做一个热心并受欢迎的人
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复 支持 反对

使用道具 举报

已领礼包: 244个

财富等级: 日进斗金

发表于 2021-6-23 11:59:25 | 显示全部楼层
厉害
论坛插件加载方法
发帖求助前要善用【论坛搜索】功能,那里可能会有你要找的答案;
如果你在论坛求助问题,并且已经从坛友或者管理的回复中解决了问题,请把帖子标题加上【已解决】;
如何回报帮助你解决问题的坛友,一个好办法就是给对方加【D豆】,加分不会扣除自己的积分,做一个热心并受欢迎的人!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|申请友链|Archiver|手机版|小黑屋|辽公网安备|晓东CAD家园 ( 辽ICP备15016793号 )

GMT+8, 2024-4-24 13:49 , Processed in 0.191868 second(s), 37 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表