You would want to attach to the Application.ApplicationEvents and listen for the BeforeQuit event. You'll also want to attach to the DraftDocument.DocumentEvents and listen for the BeforeClose event.
There are various ways to attach to these events, some better than others. I'm actually working on a blog post with GitHub samples demonstrating event handling. If you'll reply with your programming language, I'll get you a snippet to get you going.
I'll likely work on the blog post over the weekend. If you want to get a head start, I just comitted the latest Visual Basic samples on GitHub. Download the zip, extract it and look at the Applications\EventHandling\EventHandling.sln.