revit二次开发之二 删除选中的对象

对选中的对象进行删除

using System;
using System.Windows.Forms;
using System.Collections;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;

namespace Revit.SDK.Samples.DeleteObject.CS
{
    /// <summary>
    /// 删除被选中的对象
    /// </summary>
    [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Automatic)]
    public class Command : Autodesk.Revit.UI.IExternalCommand
    {
    
        public Autodesk.Revit.UI.Result Execute(
            Autodesk.Revit.UI.ExternalCommandData commandData,
            ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            Autodesk.Revit.UI.UIApplication revit = commandData.Application;

            ElementSet collection = new ElementSet();
            //获取当前选中对象的集合
            foreach (ElementId elementId in revit.ActiveUIDocument.Selection.GetElementIds())
            {
               collection.Insert(revit.ActiveUIDocument.Document.GetElement(elementId));
            }
            // 判断选中对象的尺寸
            if (collection.Size < 1)
            {
                message = "至少要选择一个被删除的对象";
                return Autodesk.Revit.UI.Result.Cancelled;
            }

            bool error = true;
            try
            {
                error = true;

                // 逐个进行删除
                IEnumerator e = collection.GetEnumerator();
                bool MoreValue = e.MoveNext();
                while (MoreValue)
                {
                    Element component = e.Current as Element;
                    revit.ActiveUIDocument.Document.Delete(component.Id);
                    MoreValue = e.MoveNext();
                }

                error = false;
            }
            catch
            {
                // 将不可删除的对象添加到elements中
                foreach (Element c in collection)
                {
                    elements.Insert(c);
                }
                message = "对象不能被删除";
                return Autodesk.Revit.UI.Result.Failed;
            }
            finally
            {
                // 提示失败
                if (error)
                {
                    TaskDialog.Show("Error", "Delete failed.");
                }
            }

            return Autodesk.Revit.UI.Result.Succeeded;
        }
    }
}
View Code

 

posted @ 2016-08-19 12:46  Min.Xiaoshuang  阅读(1624)  评论(0编辑  收藏  举报