Skip to content

Instantly share code, notes, and snippets.

@tempelmann
Last active March 8, 2020 14:15
Show Gist options
  • Save tempelmann/e9ef07f606b7cce35b3ede9ecfc4e80f to your computer and use it in GitHub Desktop.
Save tempelmann/e9ef07f606b7cce35b3ede9ecfc4e80f to your computer and use it in GitHub Desktop.
A solution to the question "How can I make the cancel button react to both the Return the the Esc keys?"
// A solution to the question "How can I make the cancel button react to both the Return the the Esc keys?"
//
// See https://stackoverflow.com/a/60570407/43615
#import "AppDelegate.h"
@interface AlertEscHandler : NSView
@end
@implementation AlertEscHandler
-(BOOL)performKeyEquivalent:(NSEvent *)event {
NSString *typed = event.charactersIgnoringModifiers;
NSEventModifierFlags mods = (event.modifierFlags & NSEventModifierFlagDeviceIndependentFlagsMask);
BOOL isCmdDown = (mods & NSEventModifierFlagCommand) != 0;
if ((mods == 0 && event.keyCode == 53) || (isCmdDown && [typed isEqualToString:@"."])) { // ESC key or cmd-.
[NSApp stopModalWithCode:1001]; // 1001 is the second button's response code
}
return [super performKeyEquivalent:event];
}
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self alertTest];
[NSApp terminate:0];
}
- (void)alertTest {
NSAlert *alert = [NSAlert new];
alert.messageText = @"alert msg";
[alert addButtonWithTitle:@"OK"];
NSButton *cancelButton = [alert addButtonWithTitle:@"Cancel"];
alert.window.defaultButtonCell = cancelButton.cell;
alert.accessoryView = [AlertEscHandler new];
NSModalResponse choice = [alert runModal];
NSLog (@"User chose button %d", (int)choice);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment