public static extern void FreeConsole();//關閉主控台 public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { AllocConsole();//開啟主控台 Console.WriteLine("以下列印出所有選取元素的ID.."); UIDocument uidoc = commandData.Application.ActiveUIDocument; //UIDocument代表「現在正開啟的模型」 Autodesk.Revit.UI.Selection.Selection selElement = uidoc.Selection; //Selection代表「使用者用滑鼠左鍵按住拖曳所選取的元件」 Autodesk.Revit.DB.Document doc = uidoc.Document; //Document類別可以用來存放模型的全部或是一部份,從uidoc存取Document屬性, //就會把整個模型放進Document類別當中 foreach (ElementId eleId in selElement.GetElementIds()) { Element ele = doc.GetElement(eleId); //以ElementId在document當中找到對應的Element元件 //Document docSingle = ele.Document; //單一的元素也有Document屬性,但在這裡我們還不會用上 Console.WriteLine(eleId.ToString() + "\t" + ele.UniqueId + "\t" + ele.Name); } Console.Read(); //如果我們想要在螢幕上看到主控台的執行成果,要用Console.Read()叫它等一下,否則它會「一閃即逝」 FreeConsole(); //和Revit配合時,一定要用程式碼將主控台關掉,如果直接把主控台視窗按掉的話,會連Revit一起關掉 return(Result.Succeeded); }
public Autodesk.Revit.UI.Result Execute (Autodesk.Revit.UI.ExternalCommandData commandData, ref string message, ElementSet elements) { // Get access to the active uidoc and doc Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = commandData.Application.ActiveUIDocument.Document; Autodesk.Revit.UI.Selection.Selection sel = uidoc.Selection; try { Reference r = sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element); Element elem = doc.GetElement(r); IList <ElementId> elemsWithinBBox = WallJoinerCmd .GetWallsIntersectBoundingBox(doc, elem) .Select(e => e.Id) .ToList(); sel.SetElementIds(elemsWithinBBox); return(Autodesk.Revit.UI.Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Autodesk.Revit.UI.Result.Cancelled); } catch (Exception ex) { Autodesk.Revit.UI.TaskDialog.Show("Exception", string.Format("Message: {0}\nStackTrace: {1}", ex.Message, ex.StackTrace)); return(Autodesk.Revit.UI.Result.Failed); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { AllocConsole();//開啟主控台 Console.WriteLine("針對特定的ID及參數名稱插入參數值.."); UIDocument uidoc = commandData.Application.ActiveUIDocument; Autodesk.Revit.UI.Selection.Selection selElement = uidoc.Selection; Autodesk.Revit.DB.Document doc = uidoc.Document; //Revit 2017一定要用Document來抓Element,不再有SelElementSet類別 Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("238494", "紀乃文到此一遊,北面牆"); dic.Add("238695", "紀乃文到此一遊,東面牆"); dic.Add("238855", "紀乃文到此一遊,西面牆"); dic.Add("238993", "紀乃文到此一遊,南面牆"); Transaction trans2 = new Transaction(doc); trans2.Start("設定參數");//裡面這個字串不能省不然會報錯 foreach (ElementId eleId in selElement.GetElementIds()) { Element ele = doc.GetElement(eleId); Console.WriteLine(eleId.ToString() + "\t" + ele.Name); this.setMark(dic, eleId, doc); } trans2.Commit(); Console.Read(); FreeConsole(); //和Revit配合時,一定要用程式碼將主控台關掉,如果直接把主控台視窗按掉的話,會連Revit一起關掉 return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { try { UIDocument uidoc = commandData.Application.ActiveUIDocument; Autodesk.Revit.UI.Selection.Selection selection = uidoc.Selection; var collectionId = selection.GetElementIds(); if (0 == collectionId.Count) { TaskDialog.Show("Revit", "You haven't selected any elements."); } else { string info = "Ids of selected elements in the document are: "; foreach (var id in collectionId) { info += "\n\t" + id.IntegerValue; } TaskDialog.Show("Revit", info); } } catch (Exception e) { message = e.Message; return(Autodesk.Revit.UI.Result.Failed); } return(Autodesk.Revit.UI.Result.Succeeded); }
private void button1_Click(object sender, EventArgs e) { Autodesk.Revit.UI.Selection.Selection selElement = uidoc.Selection; ICollection <ElementId> elementIds = selElement.GetElementIds(); foreach (ElementId elementId in elementIds) { Element elem = doc.GetElement(elementId); BoundingBoxXYZ bbx = elem.get_BoundingBox(null); //從元件取得「邊界長方體」(包覆元件邊界的長方體,如果元件本身是長方體,就會完全包覆) //OutLine是一條線,此處等於直接拿包覆長方體的對角線來定義它 Outline outline = new Outline(bbx.Min, bbx.Max);//Min及Max各是一個點,都能存取XYZ座標 BoundingBoxIntersectsFilter filterIntersection = new BoundingBoxIntersectsFilter(outline); //這個過濾器會取得「所有和這個BoundingBox相交的BoundingBox,並且傳回其所代表之元件」 IList <Element> Intersects = new FilteredElementCollector(doc).WherePasses(filterIntersection).WhereElementIsNotElementType().ToElements(); StringBuilder sb = new StringBuilder("這個元件是" + elem.Category.Name + ":" + elem.Id + ":" + elem.Name + ","); sb.AppendLine("和它相鄰的元件有:"); foreach (Element eleFiltered in Intersects) { try //這邊需要用try包起來,因為我發現有些Element似乎是沒有Category.Name的,這會發生空參考錯誤 { sb.AppendLine(eleFiltered.Category.Name + ":" + eleFiltered.Id + ":" + eleFiltered.Name); //印出相鄰元件資訊 } catch (Exception ex) { } } sb.AppendLine("======="); MessageBox.Show(sb.ToString()); } //end foreach } //end fun
public materialSelector(Document _doc, Autodesk.Revit.UI.Selection.Selection _selElement) { InitializeComponent(); this.doc = _doc; this.selElement = _selElement; //我們會做使用者選取模型的前置動作,可是是在貼材質的時候才用上,開始的材質篩選還不會用到 }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //開啟模型並選取其中一部份 UIDocument uidoc = commandData.Application.ActiveUIDocument; Autodesk.Revit.UI.Selection.Selection selElement = uidoc.Selection; Autodesk.Revit.DB.Document doc = uidoc.Document; Transaction trans = new Transaction(doc); trans.Start("設定新增參數,綁定於實體之上"); //必須先新增共用參數檔案 FileStream fileStream = File.Create(Directory.GetCurrentDirectory() + "ShareParameter.txt"); fileStream.Close(); //然後將共用參數檔案綁定到Document之上 doc.Application.SharedParametersFilename = Directory.GetCurrentDirectory() + "ShareParameter.txt"; DefinitionFile defFile = doc.Application.OpenSharedParameterFile(); //打開共用參數檔 bool bindResult = SetNewParameterToTypeWall(uidoc.Application, defFile); //呼叫方法以新增參數 if (bindResult == true) { MessageBox.Show("成功新增共享參數「牆上塗鴉」"); } trans.Commit(); return(Result.Succeeded); }
/// <summary> /// The top level command. /// </summary> /// <param name="revit">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 Result Execute(ExternalCommandData revit, ref string message, ElementSet elements) { m_app = revit.Application.Application; m_doc = revit.Application.ActiveUIDocument.Document; // Find a 3D view to use for the ray tracing operation FilteredElementCollector collector = new FilteredElementCollector(m_doc); Func <View3D, bool> isNotTemplate = v3 => !(v3.IsTemplate); m_view3D = collector.OfClass(typeof(View3D)).Cast <View3D>().First <View3D>(isNotTemplate); Autodesk.Revit.UI.Selection.Selection selection = revit.Application.ActiveUIDocument.Selection; // If skylight is selected, process it. m_skylight = null; if (selection.GetElementIds().Count == 1) { foreach (ElementId eId in selection.GetElementIds()) { Element e = revit.Application.ActiveUIDocument.Document.GetElement(eId); if (e is FamilyInstance) { FamilyInstance instance = e as FamilyInstance; bool isWindow = (instance.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Windows); bool isHostedByRoof = (instance.Host.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Roofs); if (isWindow && isHostedByRoof) { m_skylight = instance; } } } } if (m_skylight == null) { message = "This tool requires exactly one skylight to be selected."; return(Result.Cancelled); } // Find the floor to use for the measurement (hardcoded) ElementId id = new ElementId(150314); m_floor = m_doc.GetElement(id) as Floor; // Calculate the height Line line = CalculateLineAboveFloor(); // Create a model curve to show the distance Plane plane = m_app.Create.NewPlane(new XYZ(1, 0, 0), line.GetEndPoint(0)); SketchPlane sketchPlane = SketchPlane.Create(m_doc, plane); ModelCurve curve = m_doc.Create.NewModelCurve(line, sketchPlane); // Show a message with the length value TaskDialog.Show("Distance", "Distance to floor: " + String.Format("{0:f2}", line.Length)); return(Result.Succeeded); }
static void CheckSelectionChange() { Autodesk.Revit.UI.Selection.Selection selection = _uiApplication.ActiveUIDocument.Selection; ElementId IdSelection; ICollection <ElementId> selectedIds = selection.GetElementIds(); int PreviousId = 0; if (selectedIds.Count == 0) { IdSelection = null; PreviousId = 0; } else { IdSelection = selectedIds.ElementAt(selectedIds.Count - 1); PreviousId = IdSelection.IntegerValue; } int i = 0, CurrentId = 0; bool IsSecond = true;; while (true) { Thread.Sleep(500); if (IsSecond && RaisePeriodicEvent) { _PeriodicEvent.Raise(); } IsSecond = !IsSecond; selection = _uiApplication.ActiveUIDocument.Selection; selectedIds = selection.GetElementIds(); if (selectedIds.Count == 0) { IdSelection = null; CurrentId = 0; } else { IdSelection = selectedIds.ElementAt(selectedIds.Count - 1); CurrentId = IdSelection.IntegerValue; } if (CurrentId != PreviousId) { if (RaiseOnSelectionEvent) { _SelectionChangedEvent.Raise(); } PreviousId = CurrentId; i++; } } }
public static Face SelectFace(UIApplication uiapp) { Document doc = uiapp.ActiveUIDocument.Document; IEnumerable <Document> doc2 = GetLinkedDocuments( doc); Autodesk.Revit.UI.Selection.Selection sel = uiapp.ActiveUIDocument.Selection; Reference pickedRef = sel.PickObject( Autodesk.Revit.UI.Selection.ObjectType.PointOnElement, "Please select a Face"); Element elem = doc.GetElement(pickedRef.ElementId); Type et = elem.GetType(); if (typeof(RevitLinkType) == et || typeof(RevitLinkInstance) == et || typeof(Instance) == et) { foreach (Document d in doc2) { if (elem.Name.Contains(d.Title)) { Reference pickedRefInLink = pickedRef .CreateReferenceInLink(); Element myElement = d.GetElement( pickedRefInLink.ElementId); Face myGeometryObject = myElement .GetGeometryObjectFromReference( pickedRefInLink) as Face; return(myGeometryObject); } } } else { Element myElement = doc.GetElement( pickedRef.ElementId); Face myGeometryObject = myElement .GetGeometryObjectFromReference(pickedRef) as Face; return(myGeometryObject); } return(null); }
public Autodesk.Revit.DB.Reference SelectElement(Document doc, UIDocument UIdoc) { Reference selectedelement = null; try { Autodesk.Revit.UI.Selection.Selection choice = UIdoc.Selection; selectedelement = choice.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element); } catch (Exception) { throw; } return(selectedelement); }
private void CanPipeSelectExecute(object obj, Autodesk.Revit.UI.Events.CanExecuteEventArgs avgs) { if (avgs.ActiveDocument == null || avgs.ActiveDocument.Application.IsPipingAnalysisEnabled == false) { avgs.CanExecute = false; } else { UIDocument uiDocument = new UIDocument(avgs.ActiveDocument); Autodesk.Revit.UI.Selection.Selection selection = uiDocument.Selection; avgs.CanExecute = PressureLossReportHelper.instance.hasValidSystem(avgs.ActiveDocument, selection.Elements, ReportResource.pipeDomain); } }
/// <summary> /// This example use Revit API to call winform for performing automatic paint tool /// </summary> /// <param name="commandData"></param> /// <param name="message"></param> /// <param name="elements"></param> /// <returns></returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Autodesk.Revit.UI.Selection.Selection selElement = uidoc.Selection; Autodesk.Revit.DB.Document doc = uidoc.Document; //this is how we launch a windows form inside a Revit API application Application.EnableVisualStyles(); Application.Run(new F005_MaterialSelector(doc, selElement)); return(Result.Succeeded); }//end fun
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //Console.WriteLine("針對特定的ID及參數名稱插入參數值.."); UIDocument uidoc = commandData.Application.ActiveUIDocument; Autodesk.Revit.UI.Selection.Selection selElement = uidoc.Selection; //如果有上一行就表示元件有經過選擇,否則就是視同全選 Autodesk.Revit.DB.Document doc = uidoc.Document; //Revit 2017一定要用Document來抓Element,不再有SelElementSet類別 Application.EnableVisualStyles(); Application.Run(new materialSelector(doc, selElement)); return(Result.Succeeded); }//end fun
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Autodesk.Revit.UI.Selection.Selection selElement = uidoc.Selection; Autodesk.Revit.DB.Document doc = uidoc.Document; foreach (ElementId eleId in selElement.GetElementIds()) { Element ele = doc.GetElement(eleId); TaskDialog.Show("印出選取元件的id", eleId.ToString() + "\t" + ele.Name); } return(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!"); } }
static IList <Element> SelectInterferingElems(UIDocument uidoc, Document doc) { Autodesk.Revit.UI.Selection.Selection selection = uidoc.Selection; IList <Reference> references = selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, new HorizontalElementsSelectionFilter(), "Select splitting elements"); // Detect whether the selected elements intersect the main element IList <Element> selectedElems = references.Select <Reference, Element> (r => (doc.GetElement(r))).ToList <Element>(); return(selectedElems.OrderBy(e => { return ((Level)doc .GetElement(e.LevelId)).Elevation; }).ToList()); }
/// <summary> /// This example set values to the parameter we created in the previous unit /// </summary> /// <param name="commandData"></param> /// <param name="message"></param> /// <param name="elements"></param> /// <returns></returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Autodesk.Revit.UI.Selection.Selection selElement = uidoc.Selection; Autodesk.Revit.DB.Document doc = uidoc.Document; //this is the first time to use transaction object, becasue we want to modfify the BIM model Transaction trans2 = new Transaction(doc); trans2.Start("set values for parameters"); //you must give a name to the transaction, cannot be ignored int k = 1; foreach (ElementId eleId in selElement.GetElementIds()) { Element ele = doc.GetElement(eleId); this.setMark(k, eleId, doc); k++; } trans2.Commit(); MessageBox.Show("set values to parameters successfully!"); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; Autodesk.Revit.UI.Selection.Selection sel = commandData.Application.ActiveUIDocument.Selection; Reference reference = sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element); Transaction trans = new Transaction(doc); Element elem = doc.GetElement(reference); trans.Start("Create solid"); LocationCurve lc = elem.Location as LocationCurve; if (lc == null) { throw new InvalidOperationException("Current element is not a curve-dirven element"); } //Create the sweep path var pathCurveLoop = new CurveLoop(); Curve curve = lc.Curve; pathCurveLoop.Append(curve); //get the point to create a plane for the profile. XYZ xyzFirstPoint = curve.GetEndPoint(0); //Create the plane Transform transform = curve.ComputeDerivatives(0, true); XYZ xyzDirection = transform.BasisX; Plane profilePlane = Plane.CreateByNormalAndOrigin(xyzDirection.Normalize(), transform.Origin); //Create a profile which is a rectangle with height and width of 2000mm and 900mm double dblHeight = 2000 / 304.8; double dblWidth = 900 / 304.8; UV uvPt0 = new UV(0, 0) - new UV(dblWidth / 2, 0); UV uvPt1 = uvPt0 + new UV(dblWidth, 0); UV uvPt2 = uvPt1 + new UV(0, dblHeight); UV uvPt3 = uvPt2 - new UV(dblWidth, 0); XYZ xVec = profilePlane.XVec; XYZ yVec = profilePlane.YVec; XYZ xyzPt0 = profilePlane.Origin + profilePlane.XVec.Multiply(uvPt0.U) + profilePlane.YVec.Multiply(uvPt0.V); XYZ xyzPt1 = profilePlane.Origin + profilePlane.XVec.Multiply(uvPt1.U) + profilePlane.YVec.Multiply(uvPt1.V); XYZ xyzPt2 = profilePlane.Origin + profilePlane.XVec.Multiply(uvPt2.U) + profilePlane.YVec.Multiply(uvPt2.V); XYZ xyzPt3 = profilePlane.Origin + profilePlane.XVec.Multiply(uvPt3.U) + profilePlane.YVec.Multiply(uvPt3.V); Line l1 = Line.CreateBound(xyzPt0, xyzPt1); Line l2 = Line.CreateBound(xyzPt1, xyzPt2); Line l3 = Line.CreateBound(xyzPt2, xyzPt3); Line l4 = Line.CreateBound(xyzPt3, xyzPt0); CurveLoop loop = new CurveLoop(); loop.Append(l1); loop.Append(l2); loop.Append(l3); loop.Append(l4); List <CurveLoop> newloops = new List <CurveLoop>() { loop }; //Create the swept solid Solid sweepSolid = GeometryCreationUtilities.CreateSweptGeometry(pathCurveLoop, 0, lc.Curve.GetEndParameter(0), newloops); //Create a directShape to visualize the solid DirectShape ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); ds.AppendShape(new Solid[1] { sweepSolid }); trans.Commit(); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; doc = app.ActiveUIDocument.Document; massdoc = app.Application.NewFamilyDocument(@"C:\ProgramData\Autodesk\RVT 2016\Family Templates\Chinese\概念体量\公制体量.rft"); m_familyCreator = massdoc.FamilyCreate; //选择并初始化工井实例 Autodesk.Revit.UI.Selection.Selection sel = app.ActiveUIDocument.Selection; IList <Reference> familylist = sel.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, "请选择工井"); FamilyInstance well1 = doc.GetElement(familylist[0]) as FamilyInstance; FamilyInstance well2 = doc.GetElement(familylist[1]) as FamilyInstance; //初始化welldoc FilteredElementCollector collector = new FilteredElementCollector(doc); if (collector != null) { collector.OfClass(typeof(Family)); } IList <Element> list = collector.ToElements(); foreach (Element f in list) { Family family = f as Family; if (family.Name == "直通工井") { welldoc = doc.EditFamily(family); break; } } //创建电缆族文件并保存 Transaction trans = new Transaction(massdoc); trans.Start("创建新曲线"); MakeNewCurve(well1, well2); trans.Commit(); int fileNum = 0; string path; while (true) { path = "C:\\Users\\DELL\\Documents\\test" + fileNum.ToString() + ".rft"; if (!File.Exists(path)) { massdoc.SaveAs(path); break; } fileNum++; } string filename = "test" + fileNum.ToString(); //将电缆插入项目文件中 trans = new Transaction(doc); trans.Start("将曲线插入项目文件"); doc.LoadFamily(path); FamilySymbol fs = getSymbolType(doc, filename); fs.Activate(); FamilyInstance fi = doc.Create.NewFamilyInstance(XYZ.Zero, fs, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); fi.Category.Material = getMaterial(doc, "混凝土"); trans.Commit(); return(Result.Succeeded); }