c# – 提示用户选择一个组并获取该组ID的方法

我正在尝试编写一个方法,提示用户选择一个组并返回该组的ObjectId,以便我以后可以使用它.现在该方法看起来像这样:

public static ObjectId PromptUserForGroup()
        {
            using (Transaction tr = _database.TransactionManager.StartTransaction())
            using (DocumentLock docLock = _activeDocument.LockDocument())
            {

                PromptSelectionResult activeSelectionPrompt = _editor.GetSelection();
                if (activeSelectionPrompt.Status == PromptStatus.OK)
                {
                    ObjectId[] ids = activeSelectionPrompt.Value.GetObjectIds();
                    foreach (ObjectId id in ids)
                    {
                        Group groupToCheck = tr.GetObject(id, OpenMode.ForWrite) as Group;
                        if (groupToCheck != null)
                        {
                            return groupToCheck.Id;
                        }
                    }
                }
                else
                {
                    throw new IOException();
                }
                return ObjectId.Null;
            }
        }

当我调用该方法时,它会提示用户,就像我想要的那样.但是,当我选择组时,它总是返回ObjectId.Null,这意味着它没有意识到我正在选择一个组.我不知道什么是错的或如何解决它.

最佳答案 实际上,Group不是从Entity派生的,因此不在modelspace(BlockTableRecord)上.因此,图纸上没有组,但是在字典上.

当用户选择某些内容时,您需要找到它所属的组.这是一个示例代码:

[CommandMethod("FindGroup")]
static public void FindGroup()
{
  Document doc =
      Application.DocumentManager.MdiActiveDocument;
  Database db = doc.Database;
  Editor ed = doc.Editor;
  PromptEntityResult acSSPrompt =
      ed.GetEntity("Select the entity to find the group");

  if (acSSPrompt.Status != PromptStatus.OK)
    return;

  using (Transaction Tx =
      db.TransactionManager.StartTransaction())
  {
    Entity ent = Tx.GetObject(acSSPrompt.ObjectId,
                            OpenMode.ForRead) as Entity;
    ObjectIdCollection ids = ent.GetPersistentReactorIds();

    bool bPartOfGroup = false;
    foreach (ObjectId id in ids)
    {
      DBObject obj = Tx.GetObject(id, OpenMode.ForRead);

      if (obj is Group)
      {
        Group group = obj as Group;
        bPartOfGroup = true;
        ed.WriteMessage(
            "Entity is part of " + group.Name + " group\n");

      }
    }

    if (!bPartOfGroup)
      ed.WriteMessage(
              "Entity is Not part of any group\n");
    Tx.Commit();
  }
}

资料来源:http://adndevblog.typepad.com/autocad/2012/04/how-to-detect-whether-entity-is-belong-to-any-group-or-not.html

点赞