Refactor the event handling for titlebar buttons a bit.