Prevent exception when cancelling quit dialog, and refactor a bit