提示用户选择组并获取该组ID的方法

时间:2015-07-20 20:47:42

标签: c# autocad-plugin

我试图编写一个方法,提示用户选择一个组并返回该组的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,这意味着它并没有意识到我正在挑选一个组。我不知道什么是错的或者如何解决它。

1 个答案:

答案 0 :(得分:2)

实际上,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