Using events is a two step process. First, you must have a function that will handle the event notification. This function must take two parameters, the first is an Object that denotes the "sender" of the event notification, the second is an event-specific object that contains event arguments specific to that event. For example, to register the DocumentSavingAs event, your event handler must take a second parameter that is a DocumentSavingAsEventArgs object.
The second part of using an event is registering the event with Revit. This can be done as early as in the OnStartup() function through the ControlledApplication parameter, or at any time after Revit starts up. Although events can be registered for External Commands as well as External Applications, it is not recommended unless the External Command registers and unregisters the event in the same external command.
The following example registers the DocumentOpened event, and when that event is triggered, this application will set the address of the project.
Code Region 24-1: Registering Application.DocumentOpened |
public class Application_DocumentOpened : IExternalApplication { public IExternalApplication.Result OnStartup(ControlledApplication application) { try { // Register event. application.DocumentOpened += new EventHandler <Autodesk.Revit.Events.DocumentOpenedEventArgs>(application_DocumentOpened); } catch (Exception) { return Autodesk.Revit.UI.Result.Failed; } return Autodesk.Revit.UI.Result.Succeeded; } public IExternalApplication.Result OnShutdown(ControlledApplication application) { // remove the event. application.DocumentOpened -= application_DocumentOpened; return Autodesk.Revit.UI.Result.Succeeded; } public void application_DocumentOpened(object sender, DocumentOpenedEventArgs args) { // get document from event args. Document doc = args.Document; Transaction transaction = new Transaction(doc, "Edit Address"); if (transaction.Start() == TransactionStatus.Started) { doc.ProjectInformation.Address = "United States - Massachusetts - Waltham - 1560 Trapelo Road"; transaction.Commit(); } } } |