2

The Revit SDK sample for "AIPAppStartup" has prebuilt sections for code to the executed "OnShutDown" (when closing Revit session) or "OnStartup" (when starting Revit session), but I want to be able to run code for each document loaded. Specifically, I want Revit to clear out temp files associated with the particular model loaded.

I tried creating a new result, public Autodesk.Revit.UI.Result OnLoad(UIControlledApplication application), and this didn't work. I also tried another couple On**** possibilities (OnOpen, etc), which also failed.

Is there a particular "On*****" result to use which will accomplish my desire?

KeachyPeen
  • 147
  • 2
  • 13

1 Answers1

7

The event you're looking for is OnDocumentOpened, if you want it to run after the model has been opened, or OnDocumentOpening, if you want it to run before the model opens.

You will need to add event handlers into the OnStartup method of your application:

public Result OnStartup(UIControlledApplication application)  {
     application.ControlledApplication.DocumentOpened += OnDocOpened;
     //Rest of your code here...
     return Result.Succeeded;
}

private void OnDocOpened(object sender, DocumentOpenedEventArgs args) {
    Autodesk.Revit.ApplicationServices.Application app = (Autodesk.Revit.ApplicationServices.Application)sender;
    Document doc = args.Document;
    //Your code here...
}

You should also remove the event handler in the OnShutdown method of your application:

public Result OnShutdown(UIControlledApplication application) {
    application.ControlledApplication.DocumentOpened -= OnDocOpened;
    //Rest of your code here...
    return Result.Succeeded;
}
Colin Stark
  • 591
  • 3
  • 15
  • Thanks, that was helpful. What is the reason for removing the "DocumentOpened" from OnShutdown? Does it re-run code during shutdown? I hadn't removed the event handler while testing, and didn't see any difference (I had a TaskDialog that would have displayed). – KeachyPeen May 15 '14 at 13:37
  • I couldn't tell you the exact reason, but every example using Event Handlers in Revit has included the code to remove them in the OnShutdown method. – Colin Stark May 15 '14 at 20:27
  • @KeachyPeen Typically you want to remove the event handler in cases where the publisher is still triggering the event but the subscriber no longer wants to listen. See [Jon Skeet's answer to this question](http://stackoverflow.com/questions/506092/is-it-necessary-to-explicitly-remove-event-handlers-in-c-sharp). In this case it is not an issue because while Revit is open you always want it to listen and when it's not open you can't listen. In other words once the application has shut down there is no way that `OnDocOpened` could be triggered again anyway. – skeletank May 27 '14 at 13:56