vcirilli
vcirilli

Reputation: 331

How to set function keys as key equivalents programmatically

From NSMenuItem Class Reference

If you want to specify the Backspace key as the key equivalent for a menu item, use a single character string with NSBackspaceCharacter (defined in NSText.h as 0x08) and for the Forward Delete key, use NSDeleteCharacter (defined in NSText.h as 0x7F).

Not sure I understand "use a single character string with..." from the class ref.

// This works as expected

NSString *s = [NSString stringWithFormat:@"%c",NSDeleteCharacter];

    [myMenuItem setKeyEquivalentModifierMask:NSCommandKeyMask];

    [myMenuItem setKeyEquivalent:s];

enter image description here

// This doesn't works as expected

NSString *s = [NSString stringWithFormat:@"%c",NSF2FunctionKey];

    [myMenuItem setKeyEquivalentModifierMask:NSCommandKeyMask];

    [myMenuItem setKeyEquivalent:s];

enter image description here

Upvotes: 10

Views: 2943

Answers (4)

Qingyang Lin Grovy
Qingyang Lin Grovy

Reputation: 11

NSString *s = [NSString stringWithFormat:@"%C",NSF2FunctionKey];

notice capitalized %C instead of small case %c, as the former is for unichar and the latter for char

Upvotes: 0

Ky -
Ky -

Reputation: 32103

In Swift 3, 4, and 5:

let f2Character: Character = Character(UnicodeScalar(NSF2FunctionKey)!)
myMenuItem.keyEquivalent = String(f2Character)
myMenuItem.keyEquivalentModifierMask = []

Upvotes: 7

seb
seb

Reputation: 2385

Example for Swift 2.0:

let key = String(utf16CodeUnits: [unichar(NSBackspaceCharacter)], count: 1) as String
menuItem.keyEquivalentModifierMask = Int(NSEventModifierFlags.CommandKeyMask.rawValue)
menuItem.keyEquivalent = key

Upvotes: 4

vcirilli
vcirilli

Reputation: 331

Figured it out myself.

   unichar c = NSF2FunctionKey;

    NSString *f2 = [NSString stringWithCharacters:&c length:1];

    [mi setKeyEquivalent:f2];
    [mi setKeyEquivalentModifierMask:NSCommandKeyMask];

enter image description here

Upvotes: 7

Related Questions