///<summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> 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)); } // check user selection if (collection.Size < 1) { message = "Please select object(s) before delete."; return(Autodesk.Revit.UI.Result.Cancelled); } bool error = true; try { error = true; // delete selection 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 { // if revit threw an exception, try to catch it foreach (Element c in collection) { elements.Insert(c); } message = "object(s) can't be deleted."; return(Autodesk.Revit.UI.Result.Failed); } finally { // if revit threw an exception, display error and return failed if (error) { TaskDialog.Show("Error", "Delete failed."); } } return(Autodesk.Revit.UI.Result.Succeeded); }
public Autodesk.Revit.UI.Result Execute(ExternalCommandData externalCommandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { message = "Please note the highlighted walls."; var collector = new FilteredElementCollector(externalCommandData.Application.ActiveUIDocument.Document); var collection = collector.OfClass(typeof(Wall)).ToElements(); foreach (var e in collection) { elements.Insert(e); } return(Result.Failed); }
/// <summary> /// Overload this method to implement the external command within Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { ElementSet selections = new ElementSet(); foreach (ElementId elementId in commandData.Application.ActiveUIDocument.Selection.GetElementIds()) { selections.Insert(commandData.Application.ActiveUIDocument.Document.GetElement(elementId)); } ElementSet dimsToDelete = new Autodesk.Revit.DB.ElementSet(); //warning if nothing selected if (0 == selections.Size) { message = "Please select dimensions"; return(Autodesk.Revit.UI.Result.Failed); } //find all unpinned dimensions in the current selection foreach (Element e in selections) { Dimension dimesionTemp = e as Dimension; if (null != dimesionTemp && !dimesionTemp.Pinned) { dimsToDelete.Insert(dimesionTemp); } } //warning if could not find any unpinned dimension if (0 == dimsToDelete.Size) { message = "There are no unpinned dimensions currently selected"; return(Autodesk.Revit.UI.Result.Failed); } Transaction transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "External Tool"); transaction.Start(); //delete all the unpinned dimensions foreach (Element e in dimsToDelete) { commandData.Application.ActiveUIDocument.Document.Delete(e.Id); } transaction.Commit(); return(Autodesk.Revit.UI.Result.Succeeded); }
// TBD: as of 04/10/07 - only works on App startup, not dynamically from another command (jma) /*public void * AddMenu() * { * MenuItem rootMenu = m_revitApp.CreateTopMenu("RevitLookup Test Menu Item"); * * bool success = rootMenu.AddToExternalTools(); * if (success) { * MenuItem subItem = rootMenu.Append(MenuItem.MenuType.BasicMenu, "Pick me to call back into RevitLookup", "RevitLookup.dll", "CmdSampleMenuItemCallback"); * System.Windows.Forms.MessageBox.Show("Successfully added new menu to the External Tools menu. Pick the item to demonstrate callback."); * } * else * System.Windows.Forms.MessageBox.Show("Could not add new menu!"); * } * * public void * AddToolbar() * { * Toolbar toolBar = m_revitApp.CreateToolbar(); * toolBar.Name = "Jimbo"; * * if (toolBar != null) { * ToolbarItem tbItem = toolBar.AddItem("RevitLookup.dll", "CmdSampleMenuItemCallback"); * System.Windows.Forms.MessageBox.Show("Successfully added new toolbar. Pick the item to demonstrate callback."); * } * else * System.Windows.Forms.MessageBox.Show("Could not add new toolbar!"); * }*/ public void SelectElement() { Autodesk.Revit.UI.Selection.Selection selSet = m_revitApp.ActiveUIDocument.Selection; try { Autodesk.Revit.DB.Element elem = m_revitApp.ActiveUIDocument.Document.GetElement(selSet.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element).ElementId); Autodesk.Revit.DB.ElementSet elemSet = m_revitApp.Application.Create.NewElementSet(); elemSet.Insert(elem); Snoop.Forms.Objects form = new Snoop.Forms.Objects(elemSet); form.ShowDialog(); } catch (System.Exception) { System.Windows.Forms.MessageBox.Show("Didn't pick one!"); } }
ElementSet(string label, ICollection <Autodesk.Revit.DB.ElementId> val, Document doc) : base(label) { MVal = new Autodesk.Revit.DB.ElementSet(); foreach (var elemId in val) { if (Autodesk.Revit.DB.ElementId.InvalidElementId == elemId) { continue; } var elem = doc.GetElement(elemId); if (null != elem) { MVal.Insert(elem); } } }
//private void btnCancel_Click(object sender, EventArgs e) //{ // //this.Close(); //} #region convertTextNotesToUpperByView private void convertTextNotesToUpperByView() { // Iterate through the document and find all the TextNote elements FilteredElementCollector collector = new FilteredElementCollector(document, document.ActiveView.Id); collector.OfClass(typeof(TextNote)); if (collector.GetElementCount() == 0) { return; } // Record all TextNotes that are not yet formatted to be 'AllCaps' ElementSet textNotesToUpdate = new Autodesk.Revit.DB.ElementSet(); foreach (Element element in collector) { TextNote textNote = (TextNote)element; // Extract the FormattedText from the TextNote FormattedText formattedText = textNote.GetFormattedText(); if (formattedText.GetAllCapsStatus() != FormatStatus.All) { textNotesToUpdate.Insert(textNote); } } // Check whether we found any TextNotes that need to be formatted if (textNotesToUpdate.IsEmpty) { //Do something if there are no notes to format TaskDialog.Show("Nothing to do!", "There are no Text Notes to change to uppercase!"); } // Apply the 'AllCaps' formatting to the TextNotes that still need it. using (frmConvertTextNotes frm = new frmConvertTextNotes(document)) { foreach (TextNote textNote in textNotesToUpdate) { Autodesk.Revit.DB.FormattedText formattedText = textNote.GetFormattedText(); formattedText.SetAllCapsStatus(true); textNote.SetFormattedText(formattedText); } } }
public Autodesk.Revit.UI.Result Execute(ExternalCommandData externalCommandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { try { var uidoc = externalCommandData.Application.ActiveUIDocument; var doc = uidoc.Document; var ids = doc.Delete(uidoc.Selection.GetElementIds()); var taskDialog = new TaskDialog("Revit"); taskDialog.MainContent = ("Click Yes to return Succeeded. Selected members will be deleted.\n" + "Click No to return Failed. Selected members will not be deleted.\n" + "Click Cancel to return Cancelled. Selected members will not be deleted."); var buttons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel; taskDialog.CommonButtons = buttons; var taskDialogResult = taskDialog.Show(); if (taskDialogResult == TaskDialogResult.Yes) { return(Autodesk.Revit.UI.Result.Succeeded); } else if (taskDialogResult == TaskDialogResult.No) { var elementIds = uidoc.Selection.GetElementIds(); foreach (var id in elementIds) { elements.Insert(doc.GetElement(id)); } message = "Failed to delete selection."; return(Autodesk.Revit.UI.Result.Failed); } else { return(Autodesk.Revit.UI.Result.Cancelled); } } catch { message = "Unexpected Exception thrown."; return(Autodesk.Revit.UI.Result.Failed); } }
/// <summary> /// Overload this method to implement the external command within Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData, ref string message, Autodesk.Revit.DB.ElementSet elements) { ElementSet selections = commandData.Application.ActiveUIDocument.Selection.Elements; ElementSet dimsToDelete = new Autodesk.Revit.DB.ElementSet(); //warning if nothing selected if (0 == selections.Size) { message = "Please select dimensions"; return Autodesk.Revit.UI.Result.Failed; } //find all unpinned dimensions in the current selection foreach (Element e in selections) { Dimension dimesionTemp = e as Dimension; if (null != dimesionTemp && !dimesionTemp.Pinned) { dimsToDelete.Insert(dimesionTemp); } } //warning if could not find any unpinned dimension if (0 == dimsToDelete.Size) { message = "There are no unpinned dimensions currently selected"; return Autodesk.Revit.UI.Result.Failed; } Transaction transaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "External Tool"); transaction.Start(); //delete all the unpinned dimensions commandData.Application.ActiveUIDocument.Document.Delete(dimsToDelete); transaction.Commit(); return Autodesk.Revit.UI.Result.Succeeded; }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> 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; m_revit = revit; RotateFramingObjectsForm displayForm = new RotateFramingObjectsForm(this); displayForm.StartPosition = FormStartPosition.CenterParent; ElementSet selection = new ElementSet(); foreach (ElementId elementId in revit.ActiveUIDocument.Selection.GetElementIds()) { selection.Insert(revit.ActiveUIDocument.Document.GetElement(elementId)); } bool isSingle = true; //selection is single object bool isAllFamilyInstance = true; //all is not familyInstance // There must be beams, braces or columns selected if (selection.IsEmpty) { // nothing selected message = "Please select some beams, braces or columns."; return(Autodesk.Revit.UI.Result.Failed); } else if (1 != selection.Size) { isSingle = false; try { if (DialogResult.OK != displayForm.ShowDialog()) { return(Autodesk.Revit.UI.Result.Cancelled); } } catch (Exception) { return(Autodesk.Revit.UI.Result.Failed); } // return Autodesk.Revit.UI.Result.Succeeded; // more than one object selected } // if the selected elements are familyInstances, try to get their existing rotation foreach (Autodesk.Revit.DB.Element e in selection) { FamilyInstance familyComponent = e as FamilyInstance; if (familyComponent != null) { if (StructuralType.Beam == familyComponent.StructuralType || StructuralType.Brace == familyComponent.StructuralType) { // selection is a beam or brace string returnValue = this.FindParameter(AngleDefinitionName, familyComponent); displayForm.rotationTextBox.Text = returnValue.ToString(); } else if (StructuralType.Column == familyComponent.StructuralType) { // selection is a column Location columnLocation = familyComponent.Location; LocationPoint pointLocation = columnLocation as LocationPoint; double temp = pointLocation.Rotation; string output = (Math.Round(temp * 180 / (Math.PI), 3)).ToString(); displayForm.rotationTextBox.Text = output; } else { // other familyInstance can not be rotated message = "It is not a beam, brace or column."; elements.Insert(familyComponent); return(Autodesk.Revit.UI.Result.Failed); } } else { if (isSingle) { message = "It is not a FamilyInstance."; elements.Insert(e); return(Autodesk.Revit.UI.Result.Failed); } // there is some objects is not familyInstance message = "They are not FamilyInstances"; elements.Insert(e); isAllFamilyInstance = false; } } if (isSingle) { try { if (DialogResult.OK != displayForm.ShowDialog()) { return(Autodesk.Revit.UI.Result.Cancelled); } } catch (Exception) { return(Autodesk.Revit.UI.Result.Failed); } } if (isAllFamilyInstance) { return(Autodesk.Revit.UI.Result.Succeeded); } else { //output error information return(Autodesk.Revit.UI.Result.Failed); } }
/// <summary> /// Test whether each room has a roof to bound it. /// </summary> /// <param name="message">Error message to be dumped.</param> /// <param name="elements">Some elements to return.</param> /// <returns></returns> private bool FindRoomBoundingRoofs(ref string message, Autodesk.Revit.DB.ElementSet elements) { // Get all rooms List <Element> rooms = GetRoomsElements(); if (rooms.Count == 0) { message = "Unable to identify any rooms, please create room first!"; return(false); } // Represents the criteria for boundary elements to be considered bounding roofs LogicalOrFilter categoryFilter = new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_Roofs), new ElementCategoryFilter(BuiltInCategory.OST_RoofSoffit)); // Calculator for room/space geometry. SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(m_document); // Stores the resulting room->roof relationships Dictionary <Element, List <ElementId> > roomsAndRoofs = new Dictionary <Element, List <ElementId> >(); foreach (Element room in rooms) { // Get room geometry & boundaries SpatialElementGeometryResults results = calculator.CalculateSpatialElementGeometry((SpatialElement)room); // Get solid geometry so we can examine each face Solid geometry = results.GetGeometry(); foreach (Face face in geometry.Faces) { // Get list of roof boundary subfaces for a given face IList <SpatialElementBoundarySubface> boundaryFaces = results.GetBoundaryFaceInfo(face); foreach (SpatialElementBoundarySubface boundaryFace in boundaryFaces) { // Get boundary element LinkElementId boundaryElementId = boundaryFace.SpatialBoundaryElement; // Only considering local file room bounding elements ElementId localElementId = boundaryElementId.HostElementId; // Evaluate if element meets criteria using PassesFilter() if (localElementId != ElementId.InvalidElementId && categoryFilter.PassesFilter(m_document, localElementId)) { // Room already has roofs, add more if (roomsAndRoofs.ContainsKey(room)) { List <ElementId> roofs = roomsAndRoofs[room]; if (!roofs.Contains(localElementId)) { roofs.Add(localElementId); } } // Room found first roof else { List <ElementId> roofs = new List <ElementId>(); roofs.Add(localElementId); roomsAndRoofs.Add(room, roofs); } break; } } } } // Format results if (roomsAndRoofs.Count > 0) { String logs = String.Format("Rooms that have a bounding roof:"); message += logs + "\t\r\n"; Trace.WriteLine(logs); foreach (KeyValuePair <Element, List <ElementId> > kvp in roomsAndRoofs) { // remove this room from all rooms list rooms.Remove(kvp.Key); List <ElementId> roofs = kvp.Value; String roofsString; // Single roof boundary if (roofs.Count == 1) { Element roof = m_document.GetElement(roofs[0]); roofsString = String.Format("Roof: Id = {0}, Name = {1}", roof.Id.IntegerValue, roof.Name); } // Multiple roofs else { roofsString = "Roofs ids = " + string.Join(", ", Array.ConvertAll <ElementId, string>(roofs.ToArray(), i => i.ToString())); } // Save results logs = String.Format( " Room: Id = {0}, Name = {1} --> {2}", kvp.Key.Id.IntegerValue, kvp.Key.Name, roofsString); message += logs + "\t\r\n"; Trace.WriteLine(logs); } } // Format the rooms that have no bounding roof Trace.WriteLine("Geometry relationship checking finished..."); if (rooms.Count != 0) { String logs = String.Format("Below rooms don't have bounding roofs:"); message += logs + "\t\r\n"; Trace.WriteLine(logs); foreach (Element room in rooms) { elements.Insert(room); logs = String.Format(" Room Id: {0}, Room Name: {1}", room.Id.IntegerValue, room.Name); message += logs + "\t\r\n"; Trace.WriteLine(logs); } } return(true); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user cancelled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public virtual Result Execute(ExternalCommandData commandData , ref string message, ElementSet elements) { try { Document document = commandData.Application.ActiveUIDocument.Document; // Iterate through the document and find all the TextNote elements FilteredElementCollector collector = new FilteredElementCollector(document); collector.OfClass(typeof(TextNote)); if (collector.GetElementCount() == 0) { message = "The document does not contain TextNote elements"; return(Result.Failed); } // Record all TextNotes that are not yet formatted to be 'AllCaps' ElementSet textNotesToUpdate = new Autodesk.Revit.DB.ElementSet(); foreach (Element element in collector) { TextNote textNote = (TextNote)element; // Extract the FormattedText from the TextNote FormattedText formattedText = textNote.GetFormattedText(); // If 'GetAllCapsStatus()' returns 'FormatStatus.All' then all the characters in // the text have the 'AllCaps' status. // If there are no characters that have the 'AllCaps' status then 'GetAllCapsStatus()' // will return 'FormatStatus.None'. And if only some of the characters have // the 'AllCaps' status then 'GetAllCapsStatus()' returns 'FormatStatus.Mixed' // // Note that it is also possible to test whether all characters are // bold, italic, underlined, or have superscript or subscript formatting. // See 'GetBoldStatus', 'GetItalicStatus', 'GetUnderlineStatus', // 'GetSuperscriptStatus', and 'GetSubscriptStatus' respectively. // // Note that it is also possible to only test a subset of characters in the FormattedText // This is done by calling these methods with a 'TextRange' that specifies // the range of characters to be tested. if (formattedText.GetAllCapsStatus() != FormatStatus.All) { textNotesToUpdate.Insert(textNote); } } // Check whether we found any TextNotes that need to be formatted if (textNotesToUpdate.IsEmpty) { message = "No TextNote elements needed updating"; return(Result.Failed); } // Apply the 'AllCaps' formatting to the TextNotes that still need it. using (Transaction transaction = new Transaction(document, "Capitalize All TextNotes")) { transaction.Start(); foreach (TextNote textNote in textNotesToUpdate) { Autodesk.Revit.DB.FormattedText formattedText = textNote.GetFormattedText(); // Apply the 'AllCaps' status to all characters. // Note that there are also methods to apply bold, italic, underline, // superscript and subscript formatting. // And that the formatting can be applied both to the entire text // (as is done here), or to a subset by calling these methods with a 'TextRange' formattedText.SetAllCapsStatus(true); // After making the changes to the Formatted text // it is necessary to apply them to the TextNote element // (or elements) that should get these changes. textNote.SetFormattedText(formattedText); } transaction.Commit(); } return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }