Cut, copy and paste in LSUIElement applications

Copy and paste don’t work by default in applications that don’t have a menu bar – also known as LSUIElement applications. (Some people confusingly call them menu bar applications, because they often use an NSStatusItem to put an icon in the right hand side of the menu bar).

You can, in fact, copy and paste by right-clicking, but many people don’t find that and think it’s just not available.

Here’s how to enable application-wide standard keyboard shortcuts for Cut, Copy, Paste, Undo and Select All. (According to the internets, having a main menu – even though not displayed – containing a standard Edit menu would do the trick, but this no longer works (assuming it ever did)).

Put this in a subclass of NSApplication and alter the principal class in your Info.plist accordingly.

(Thanks to G for pointing out the operator precedence bug in the redo section. This is fixed now.)

- (void) sendEvent:(NSEvent *)event {
	if ([event type] == NSKeyDown) {
		if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask) {
			if ([[event charactersIgnoringModifiers] isEqualToString:@"x"]) {
				if ([self sendAction:@selector(cut:) to:nil from:self])
					return;
			}
			else if ([[event charactersIgnoringModifiers] isEqualToString:@"c"]) {
				if ([self sendAction:@selector(copy:) to:nil from:self])
					return;
			}
			else if ([[event charactersIgnoringModifiers] isEqualToString:@"v"]) {
				if ([self sendAction:@selector(paste:) to:nil from:self])
					return;
			}
			else if ([[event charactersIgnoringModifiers] isEqualToString:@"z"]) {
				if ([self sendAction:@selector(undo:) to:nil from:self])
					return;
			}
			else if ([[event charactersIgnoringModifiers] isEqualToString:@"a"]) {
				if ([self sendAction:@selector(selectAll:) to:nil from:self])
					return;
			}
		}
		else if (([event modifierFlags] & NSDeviceIndependentModifierFlagsMask) == 
								(NSCommandKeyMask | NSShiftKeyMask)) {
			if ([[event charactersIgnoringModifiers] isEqualToString:@"Z"]) {
				if ([self sendAction:@selector(redo:) to:nil from:self])
					return;
			}
		}
	}
	[super sendEvent:event];
}
This entry was posted in Uncategorized. Bookmark the permalink.

Comments are closed.