Esc and Enter keys in Cocoa dialog
-
09-06-2019 - |
Question
How can I dismiss dialog in Cocoa application when user presses Esc or Enter key? I have OK button, is it possible to make it default button?
Solution
If you present the alert panel using the NSAlert
class or, NSRunAlertPanel
family of functions, or the NSBeginAlertSheet
family of functions, you will get support for default and cancel buttons automatically.
If you're presenting a sheet that needs OK/Cancel buttons, and you're not using any of the above, you should be able to assign your buttons appropriate keyboard equivalents in Interface Builder using the attributes inspector. (Just highlight the Key Equiv. area and press the key you want to be equivalent to pressing that button.)
If you're presenting a dialog that's not either an alert or a document/window-modal sheet — don't. :) Document-modal alerts aren't Mac-like, and shouldn't be used for things like preferences windows.