You can use this osx library: com.apple.eawt.ApplicationListener
handleQuit(ApplicationEvent event)
Probably this trick.
Information from the documents:
Invoked when an application dispatches a Quit event. This event is generated when the user selects Quit from the application menu, when the user types Command-Q, or when the user control clicks on the icon of your application in the Dock and selects Quit. You can accept or decline the exit request.
Of course, this solution will not work on Windows. As far as I know, there is no universal solution, so this is probably the best way.
Aloys source share