UIApplication is a crucial class for developers as it offers access to "UI customization methods, events, the main window, and the active document."
Fortunately, an instance of this class can be obtained from various locations. For instance:
When an IExternalCommand class is executed, you can retrieve it from the provided parameter ExternalCommandData. See this example.
public override Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; //... more code statements }
Another possible way to access it is when an ExternalEvent triggers an event to execute an instance of IExternalEventHandler. The implementation of this interface includes a method Execute that takes a parameter UIApplication. After executing the method, you can capture this instance.
public void Execute(UIApplication uiApp)
In addition to that, another way to access it is by initializing it if you already have access to the ApplicationServices.Application instance. The object itself can be retrieved using Document.Application, and then we initialize a new instance of the UI application from this object.
UIApplication uiapp = new UIApplication(Doc.Application);
Also, when Revit initializes early on, refer to this code sample for a clearer illustration.
public virtual Result OnStartup(UIControlledApplication application) { application.ControlledApplication.ApplicationInitialized += ControlledApplication_ApplicationInitialized; //... more code statements } void ControlledApplication_ApplicationInitialized(object sender, Autodesk.Revit.DB.Events.ApplicationInitializedEventArgs e) { Autodesk.Revit.ApplicationServices.Application m_app = sender as Autodesk.Revit.ApplicationServices.Application; UIApplication uiApp = new UIApplication(m_app); }
Similarly to the Application Initialized event, we can also utilize idling and other events from the startup.
UIControlledApplication UcApp; public virtual Result OnStartup(UIControlledApplication application) { UcApp = application; application.Idling += GetUiApp; //... more code statements } protected void GetUiApp(object sender, Autodesk.Revit.UI.Events.IdlingEventArgs e) { UcApp.Idling -= GetUiApp; UIApplication UiApp = sender as UIApplication; OnIdling(); }
Maybe there are more ways to fetch this instance. So far, I believe all the possibilities mentioned above are sufficient to obtain a hold of this class instance.