Sharp Develop C# RotateAll example

This is an example macro that will rotate several objects 90 degrees around each objects center point.

For example, if a room has several ceiling mounted lights, and you want to rotate the lights so they run the other direction, but you want each light to stay in the same position. With the standard Revit rotate, the positions of the light will change, or you must rotate each light one by one. With this macro, each light will rotate around its center point, and you may have to move all the lights back into position, but its much easier than having to rotate or move each light individually.

Code includes an examples of allowing user selection of objects, getting an objects bounding box and center point, and the ElementTransformUtils.RotateElement.

Here is the code:

public void RotateAll()

{

UIDocument uidoc = ActiveUIDocument;

Document doc = ActiveUIDocument.Document;

Autodesk.Revit.DB.View pView = ActiveUIDocument.Document.ActiveView;

Autodesk.Revit.DB.Transaction t = new Autodesk.Revit.DB.Transaction(doc, "Rotate");

t.Start();

try

{

// Select some elements in Revit before invoking this command

// Get the element selection of current document.

Selection selection = uidoc.Selection;

ICollection<ElementId> selectedIds = uidoc.Selection.GetElementIds();

Element element = null;

if (0 == selectedIds.Count)

{

// If no elements selected.

TaskDialog.Show("Revit","You haven't selected any elements.");

}

else

{

foreach (ElementId id in selectedIds)

{

element = doc.GetElement(id);

BoundingBoxXYZ box = element.get_BoundingBox(doc.ActiveView);

if (null == box)

{

throw new Exception("Selected element doesn't contain a bounding box.");

}

//string info = "Bounding box is enabled: " + box.Enabled.ToString() + box.Max.ToString() + box.Min.ToString();

//TaskDialog.Show("Revit",info);

XYZ p1 = new XYZ((box.Min.X + box.Max.X)/2, (box.Min.Y + box.Max.Y)/2, 0);

XYZ p2 = new XYZ((box.Min.X + box.Max.X)/2, (box.Min.Y + box.Max.Y)/2, 10);

//XYZ p1 = new XYZ (0,0,0);

//XYZ p2 = new XYZ(0,0,10);

Line axis = Line.CreateBound(p1, p2);

ElementTransformUtils.RotateElement(doc, id, axis, Math.PI/2);

}

///ICollection<ElementId> copiedIds = ElementTransformUtils.CopyElements(doc, selectedIds, new XYZ(10,10,0));

}

}

catch

{

MessageBox.Show("Revit Error", "Error copying elements.");

}

t.Commit();

}// end Rotateall