Graham Lea
Graham Lea

Reputation: 6333

How do I disable these keyboard shortcuts in a NSTextView?

I have an NSTextView which I'm kind of using as a full-screen canvas for letters.

The following key combinations do things that I don't want to do (e.g. hide my window, lock up the computer).

How can I disable them to stop them being invoked?

Upvotes: 2

Views: 1038

Answers (2)

hollow7
hollow7

Reputation: 1506

Override the NSEvents for these key combinations to do nothing instead of what they will normally be doing.

Upvotes: 0

Francis McGrew
Francis McGrew

Reputation: 7272

First, make sure you understand the path of key events and user interface validation.

I think the best way to disable the actions you mention is by subclassing NSTextView and disabling their associated menu items by declaring your text view as conforming to NSUserInterfaceValidations and writing the validation method:

- (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)anItem {

    SEL action = [anItem action];
    if (@selector(selectAll:) == action ||                    // command-a
        @selector(centerSelectionInVisibleArea:) == action || // command-j
        @selector(print:) == action ||                        // command-p
        @selector(underline:) == action) {                    // command-u

        return NO;
    }
    else return [super validateUserInterfaceItem:anItem];
}

However that doesn't prevent the user from hiding the app via Command+H. To disable that key combo you can either remove its key equivalent in the MainMenu XIB, or you can subclass NSApplication and override hide:

Upvotes: 3

Related Questions