public void Execute(UIApplication uiapp) { UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; try { string result = "F"; TransactionGroup tr = new TransactionGroup(doc); tr.Start("Save As"); result = Save_As(uiapp, doc); tr.Assimilate(); if (result == "S") { doc.Save(); string pa = doc.PathName; File.Copy(pa, path.Text + "\\" + name.Text + ".rvt", true); RevitCommandId saveDoc = RevitCommandId.LookupPostableCommandId(PostableCommand.Undo); uiapp.PostCommand(saveDoc); Data_File(path.Text + "\\" + name.Text + ".rvt", doc); MessageBox.Show("Save As Success!", "SUCCESS", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message); } return; }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; Document doc = uiapp.ActiveUIDocument.Document; Demo1Updater closeUpdater = new Demo1Updater(uiapp.ActiveAddInId); if (UpdaterRegistry.IsUpdaterRegistered(closeUpdater.GetUpdaterId())) { UpdaterRegistry.UnregisterUpdater(closeUpdater.GetUpdaterId()); } //注册更新 Demo1Updater demo1Updater = new Demo1Updater(uiapp.ActiveAddInId); UpdaterRegistry.RegisterUpdater(demo1Updater); ElementCategoryFilter roomFilter = new ElementCategoryFilter(BuiltInCategory.OST_Rooms); UpdaterRegistry.AddTrigger(demo1Updater.GetUpdaterId(), roomFilter, Element.GetChangeTypeElementAddition()); RevitCommandId room_CommandId = RevitCommandId.LookupPostableCommandId(PostableCommand.Room); if (uiapp.CanPostCommand(room_CommandId)) { uiapp.PostCommand(room_CommandId); } ////注销更新 //UpdaterRegistry.UnregisterUpdater(demo1Updater.GetUpdaterId()); return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; try { // External tool commands defined by add-ins are identified by the client id specified in // the add-in manifest. It is also listed in the journal file when the command is launched manually. string name = "BA2E663D-EFAF-4E11-B304-923314D8817D"; // --> Chiama l'Add-in PluginConfiguration RevitCommandId id_addin_external_tool_cmd = RevitCommandId.LookupCommandId( name); uiapp.PostCommand(id_addin_external_tool_cmd); return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; // Built-in Revit commands are listed in the // PostableCommand enumeration RevitCommandId id_built_in = RevitCommandId.LookupPostableCommandId( PostableCommand.SheetIssuesOrRevisions); // External tool commands defined by add-ins are // identified by the client id specified in // the add-in manifest. It is also listed in the // journal file when the command is launched // manually. string name = "64b3d907-37cf-4cab-8bbc-3de9b66a3efa"; // --> id 35024 RevitCommandId id_addin_external_tool_cmd = RevitCommandId.LookupCommandId( name); uiapp.PostCommand(id_addin_external_tool_cmd); return(Result.Succeeded); }
static void CloseDocByCommand(UIApplication uiapp) { RevitCommandId closeDoc = RevitCommandId.LookupPostableCommandId( PostableCommand.Close); uiapp.PostCommand(closeDoc); }
/// <summary> /// Open a default 3d view /// <reference>https://forums.autodesk.com/t5/revit-api-forum/generate-3d-view-programmatically/td-p/5808509</reference> /// </summary> public void Open3DView() { RevitCommandId commandId = RevitCommandId.LookupPostableCommandId(PostableCommand.Default3DView); if (RvtUiApp.CanPostCommand(commandId)) { RvtUiApp.PostCommand(commandId); } }
/// <summary> /// External Event Implementation /// </summary> /// <param name="app"></param> public void Execute(UIApplication app) { try { UIDocument uiDoc = app.ActiveUIDocument; Document doc = uiDoc.Document; Autodesk.Revit.DB.View curView = null; View3D usableView = null; //if the current view is 3d (future correction => valid for IFC import) if (doc.ActiveView.ViewType != ViewType.ThreeD) { //try to use an existing 3D view IEnumerable <View3D> viewcollector3D = get3DViews(doc); if (viewcollector3D.Any(o => o.Name == "{3D}" || o.Name == "BCFortho" || o.Name == "BCFpersp")) { usableView = viewcollector3D.First(o => o.Name == "{3D}" || o.Name == "BCFortho" || o.Name == "BCFpersp"); } // No valid view to use for importing if (usableView == null) { System.Windows.MessageBox.Show("Bim snippet can't be imported since\n the project contains no valid view."); return; } // set the view to a usableView for importing the IFC snippet uiDoc.ActiveView = usableView; } // Show the import screen app.PostCommand(RevitCommandId.LookupCommandId("ID_IFC_LINK")); //Run a background worker to insert the name of the file to import BackgroundWorker bgw = new BackgroundWorker(); bgw.DoWork += new DoWorkEventHandler(DoWork); bgw.RunWorkerCompleted += (_, __) => { if (curView != null) { uiDoc.ActiveView = curView; } }; bgw.RunWorkerAsync(); } catch (Exception e) { System.Windows.MessageBox.Show("A service has failed."); } }
/// <summary> /// The function that is called to finish the execution of the workflow. Cleans up subscribed events, /// and posts the save command. /// </summary> /// <param name="uiApp"></param> private void CleanupAfterRevisionEdit(UIApplication uiApp) { // Remove dialog box showing uiApp.DialogBoxShowing -= HideDocumentNotSaved; if (binding != null) { binding.BeforeExecuted -= ReactToRevisionsAndSchedulesCommand; } externalEvent = null; // Repost the save command uiApp.PostCommand(RevitCommandId.LookupPostableCommandId(PostableCommand.Save)); }
//This method is activated by double clicking a row in teh DataGridView so show / zoom too the elements associated with the warning private void dgWarnings_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { //create a RevitCommandId to utilize Revit's built in SelectionBox feature for our selected ElementIds RevitCommandId rvtId = RevitCommandId.LookupPostableCommandId(PostableCommand.SelectionBox); //Get the ElementIds associated with the Warning from the DataGridView ICollection <ElementId> eId = (ICollection <ElementId>)dgWarnings.Rows[e.RowIndex].Cells[2].Value; //Don't know why, but without creating another ICollection and setting it, the SelectionBox will not work ICollection <ElementId> iDs = eId; //Use a try statment so an error won't crash revit try { //Get the first element in the Document from the list of Warning Elements if (doc.GetElement(iDs.FirstOrDefault()) is Element elem) { //Use this check to see if it is a view item like a Room Tag if (elem.ViewSpecific) { //If it is a view item, then open and change to that view View view = doc.GetElement(elem.OwnerViewId) as View; uiApp.ActiveUIDocument.ActiveView = view; } else { //If it is a 3D element, then provide a selection box around all elements for that warning uiApp.PostCommand(rvtId); } //Sets the current selection to the Warning Element(s) uiApp.ActiveUIDocument.Selection.SetElementIds(iDs); } } //Catch any errors and display a Dialog with the informaiton catch (Exception ex) { TaskDialog.Show("Cell Double Click Error", ex.ToString()); } }
public static void PostCmd_rotate(UIApplication uiapp) { Selection sel = uiapp.ActiveUIDocument.Selection; sel.SetElementIds(new List <ElementId> { tempFi1.Id }); var commandId = RevitCommandId.LookupPostableCommandId(PostableCommand.Rotate); if (uiapp.CanPostCommand(commandId)) { uiapp.PostCommand(commandId); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; RevitCommandId id_addin_button_cmd = RevitCommandId.LookupPostableCommandId( (PostableCommand)6417); uiapp.PostCommand(id_addin_button_cmd); return(Result.Succeeded); }
/// <summary> /// Metodo che chiude il documento attivo /// </summary> /// <remarks> /// </remarks> /// <param name="uiapp">L'oggetto Applicazione di Revit</param> private void CloseDocByCommand(UIApplication uiapp) { if (uiapp.ActiveUIDocument.Document != null) { Document doc = uiapp.ActiveUIDocument.Document; // Dà il comando di chiusura del documento aperto RevitCommandId closeDoc = RevitCommandId.LookupPostableCommandId( PostableCommand.Close); uiapp.PostCommand(closeDoc); // Assegno alla comboBox della View il valore predefinito modelessForm.AssignValueComboBoxDefault(); } }
/// <summary> /// Prompts to edit the revision and resave. /// </summary> /// <param name="application"></param> private void PromptToEditRevisionsAndResave(UIApplication application) { // Setup external event to be notified when activity is done externalEvent = ExternalEvent.Create(new PostCommandRevisionMonitorEvent(this)); // Setup event to be notified when revisions command starts (this is a good place to raise this external event) RevitCommandId id = RevitCommandId.LookupPostableCommandId(PostableCommand.SheetIssuesOrRevisions); if (binding == null) { binding = application.CreateAddInCommandBinding(id); } binding.BeforeExecuted += ReactToRevisionsAndSchedulesCommand; // Post the revision editing command application.PostCommand(id); }
public static void PostCmd_copy(UIApplication uiapp) { //用以监控新生成的tempFi uiapp.Application.DocumentChanged += new EventHandler <DocumentChangedEventArgs>(OnDocumentChanged); Selection sel = uiapp.ActiveUIDocument.Selection; sel.SetElementIds(new List <ElementId> { tempFi1.Id }); var commandId = RevitCommandId.LookupPostableCommandId(PostableCommand.Copy); if (uiapp.CanPostCommand(commandId)) { uiapp.PostCommand(commandId); } }
/// <summary> /// 提示编辑修订版本号,并重新保存 /// </summary> /// <param name="application"></param> private void PromptToEditRevisionsAndResave(UIApplication application) { // Setup external event to be notified when activity is done externalEvent = ExternalEvent.Create(new PostCommandRevisionMonitorEventHandler(this)); // Setup event to be notified when revisions command starts (this is a good place to raise this external event) RevitCommandId id = RevitCommandId.LookupPostableCommandId(PostableCommand.SheetIssuesOrRevisions); if (binding == null) { binding = application.CreateAddInCommandBinding(id); } binding.BeforeExecuted += ReactToRevisionsAndSchedulesCommand; //在执行RevitCommandId之前,执行externalEvent,也就是 CleanupAfterRevisionEdit 方法,这个方法注销了注册的事件,并 repost了 Save 命令 //这里为什么要使用外部事件?先执行屏蔽“未保存文件”对话框,然后外部事件排队,执行修订命令的对话框,执行结束后revit空闲,这里才执行 CleanupAfterRevisionEdit 方法,注销事件(以防止影响到其他命令),在调用保存方法。 // Post the revision editing command application.PostCommand(id); }
public static void ProjectBrowserOnOff(UIApplication uiApp, NewForm ui, Document doc) { Util.LogThreadInfo("Project Browser On Off"); // rename all the sheets, but first open a transaction using (Transaction t = new Transaction(doc, "Project Browser On Off")) { Util.LogThreadInfo("Project Browser On Off Transaction"); // start a transaction within the valid Revit API context t.Start("Project Browser On Off"); // our command is a postable command RevitCommandId id_built_in = RevitCommandId.LookupPostableCommandId(PostableCommand.ProjectBrowser); uiApp.PostCommand(id_built_in); t.Commit(); t.Dispose(); } }
public static void SetThinLines( UIApplication app, bool makeThin) { bool isAlreadyThin = IsThinLines(); if (makeThin != isAlreadyThin) { // Switch TL state by invoking // PostableCommand.ThinLines RevitCommandId commandId = RevitCommandId.LookupPostableCommandId( PostableCommand.ThinLines); if (app.CanPostCommand(commandId)) { app.PostCommand(commandId); } } }
static async void RunCommands( UIApplication uiapp, RevitCommandId id_addin) { uiapp.PostCommand(id_addin); await Task.Delay(400); SendKeys.Send("{ENTER}"); await Task.Delay(400); SendKeys.Send("{ENTER}"); await Task.Delay(400); SendKeys.Send("{ENTER}"); await Task.Delay(400); SendKeys.Send("{ESCAPE}"); await Task.Delay(400); SendKeys.Send("{ESCAPE}"); }
void needsCollaboration(Object sender) { if (current != null) { Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application; UIApplication uiapp = new UIApplication(app); var filter = Builders <BsonDocument> .Filter.Eq("_id", current["_id"]); var update = Builders <BsonDocument> .Update.Set("is_running", true); collection.UpdateOne(filter, update); uiapp.OpenAndActivateDocument(_test_project_filepath); RevitCommandId closeDoc = RevitCommandId.LookupPostableCommandId(PostableCommand.Close); uiapp.PostCommand(closeDoc); } else { closeRevit(); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; // External tool commands defined by add-ins are // identified by the string listed in the // journal file when the command is launched // manually. string name_addin_button_cmd = "CustomCtrl_%CustomCtrl_%" + "Add-Ins%Post Add-in Command%Dummy2"; // --> id 6417 RevitCommandId id_addin_button_cmd = RevitCommandId.LookupCommandId( name_addin_button_cmd); uiapp.PostCommand(id_addin_button_cmd); return(Result.Succeeded); }
public override void ShutDown(bool shutDownHost) { DisposeLogic.IsShuttingDown = true; OnShuttingDown(); base.ShutDown(shutDownHost); // unsubscribe events RevitServicesUpdater.UnRegisterAllChangeHooks(); UnsubscribeDocumentManagerEvents(); UnsubscribeRevitServicesUpdaterEvents(); UnsubscribeTransactionManagerEvents(); if (shutDownHost) { // this method cannot be called without Revit 2014 var exitCommand = RevitCommandId.LookupPostableCommandId(PostableCommand.ExitRevit); UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication; IdlePromise.ExecuteOnIdleAsync( () => { if (uiapp.CanPostCommand(exitCommand)) { uiapp.PostCommand(exitCommand); } else { MessageBox.Show( "A command in progress prevented Dynamo from closing revit. Dynamo update will be cancelled."); } }); } }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Autodesk.Revit.ApplicationServices.Application app = uiapp.Application; Document doc = uidoc.Document; ICollection <ElementId> viewIdCollection = new List <ElementId>(); #region void SetCollectionToRemove() { try { #region // To add all views to collection FilteredElementCollector viewCollector = new FilteredElementCollector(doc); viewCollector.OfClass(typeof(Autodesk.Revit.DB.View)); string activeViewName = uidoc.ActiveView.Name; foreach (Autodesk.Revit.DB.View v in viewCollector) { if (v.ViewType.ToString() != "ProjectBrowser" && v.ViewType.ToString() != "SystemBrowser" && v.Name != activeViewName) { viewIdCollection.Add(v.Id); } } #endregion #region // To add all project parameters to collection BindingMap bindingMap = doc.ParameterBindings; FilteredElementCollector parameterElementCollector = new FilteredElementCollector(doc); parameterElementCollector.OfClass(typeof(ParameterElement)); foreach (ParameterElement parameterElement in parameterElementCollector) { if (bindingMap.Contains(parameterElement.GetDefinition())) { viewIdCollection.Add(parameterElement.Id); } } #endregion PurgeUnused(); TaskDialog.Show("Revit Handy Tools - Model Transmit", "The project will be prepared for model transmit"); } catch (Exception e) { TaskDialog.Show("Error", e.ToString()); } } #endregion void PurgeUnused() { // To purge a project RevitCommandId commandId = RevitCommandId.LookupCommandId("ID_PURGE_UNUSED"); uiapp.PostCommand(commandId); } CustomForms.WarningForm warningTransmit = new CustomForms.WarningForm(); warningTransmit.WarningLabel = String.Format("{0}{1}", "This will remove critical settings of the project.\n", "Please make sure you run this extension in a coordiantion model."); warningTransmit.ShowDialog(); if (warningTransmit.DialogResult == DialogResult.Yes) { SetCollectionToRemove(); } else { return(Result.Succeeded); } using (Transaction tx = new Transaction(doc)) { tx.Start("Cleaning up a project for model transmit"); doc.Delete(viewIdCollection); tx.Commit(); } return(Result.Succeeded); }
/// <summary> /// Launches specific version of Dynamo command /// </summary> /// <param name="product">DynamoProduct to launch</param> /// <param name="e">Command executed event argument</param> /// <param name="playlist">Launch the Playlist app or just Dynamo</param> /// <returns>true for success</returns> private bool LaunchDynamoCommand(DynamoProduct product, ExecutedEventArgs e, bool playlist = false) { if (uiControlledApplication == null) { throw new InvalidOperationException(); } var revitVersion = uiControlledApplication.ControlledApplication.VersionNumber; var path = GetDynamoRevitPath(product, revitVersion); var data = new VersionSelectorData() { RevitVersion = revitVersion, SelectedVersion = product.VersionInfo }; data.WriteToRegistry(); //Initialize application var ass = Assembly.LoadFrom(path); var revitApp = ass.CreateInstance("Dynamo.Applications.DynamoRevitApp"); if (null == revitApp) { return(false); } //Remove the command binding, because now DynamoRevitApp will //do the command binding for DynamoRevit command. RemoveCommandBinding(); var type = revitApp.GetType(); var result = type.GetMethod("OnStartup").Invoke(revitApp, new object[] { uiControlledApplication }); if ((Result)result != Result.Succeeded) { return(false); } UIApplication uiApp = new UIApplication(e.ActiveDocument.Application); if (!playlist) { //Invoke command string message = string.Empty; result = type.GetMethod("ExecuteDynamoCommand").Invoke(revitApp, new object[] { e.GetJournalData(), uiApp }); if ((Result)result != Result.Succeeded) { return(false); } } else { //Dependent components have done a re-binding of Playlist command in order to be executed in their context. //In order to lunch the Playlist we just need to post the command to the Revit application. var dynamoPlayerCmdId = RevitCommandId.LookupCommandId("ID_PLAYLIST_DYNAMO"); if (dynamoPlayerCmdId != null) { uiApp.PostCommand(dynamoPlayerCmdId); } } uiControlledApplication = null; //release application, no more needed. return(true); }
public void Execute(UIApplication app) { if (App.docdict.Keys.Count == 0) { return; } TransactWithCentralOptions transact = new TransactWithCentralOptions(); SynchLockCallback transCallBack = new SynchLockCallback(); transact.SetLockCallback(transCallBack); SynchronizeWithCentralOptions syncset = new SynchronizeWithCentralOptions(); RelinquishOptions relinquishoptions = new RelinquishOptions(true) { CheckedOutElements = true }; syncset.SetRelinquishOptions(relinquishoptions); App.running = true; if (relinquish) { foreach (Document doc in App.docdict.Keys) { try { WorksharingUtils.RelinquishOwnership(doc, relinquishoptions, transact); } catch { } } relinquish = false; } if (sync) { if (App.Dismiss()) { sync = false; App.running = false; return; } app.Application.FailuresProcessing += FailureProcessor; bool syncfailed = false; foreach (Document doc in App.docdict.Keys) { try { if (docdict[doc]) { doc.SynchronizeWithCentral(transact, syncset); app.Application.WriteJournalComment("AutoSync", true); } } catch { syncfailed = true; } } app.Application.FailuresProcessing -= FailureProcessor; if (syncfailed) { countdown -= retrysync; } sync = false; } if (close) { if (App.Dismiss()) { App.running = false; close = false; return; } bool closelast = false; string activepathname = app.ActiveUIDocument.Document.PathName; List <Document> docsdeletelist = new List <Document>(); foreach (Document doc in App.docdict.Keys) { if (activepathname == doc.PathName) { closelast = true; } else { docsdeletelist.Add(doc); } } foreach (Document doc in docsdeletelist) { try { doc.Close(false); } catch { } } if (closelast) { RevitCommandId closeDoc = RevitCommandId.LookupPostableCommandId(PostableCommand.Close); app.PostCommand(closeDoc); } close = false; countdown = 0; } App.running = false; transact.Dispose(); syncset.Dispose(); relinquishoptions.Dispose(); }
// 绘图操作的启动与终止 /// <summary> /// 启动绘图操作 /// </summary> private void ActiveDraw() { rvtUiApp.PostCommand(RevitCommandId.LookupPostableCommandId(PostableCommand.ModelLine)); }