Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the trick behind "launch application holding [modifier key]"?

Tags:

macos

cocoa

iTunes and Reeder (and I'm sure lots of other) applications has an ability to modify startup behavior whenever they are launched while holding ⌥ (option) key. I tried looking at NSApplicationDelegate methods, but none seem to add any sort of hint to what I'm looking for. How is this functionality achieved?

like image 366
Eimantas Avatar asked Sep 11 '11 07:09

Eimantas


2 Answers

In your application delegate's applicationDidFinishLaunching: method

NSUInteger flags = ([NSEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask);

BOOL isOptionPressed = (flags == NSAlternateKeyMask);

(Edited to match awesome answer Declaring and checking/comparing (bitmask-)enums in Objective-C Previously this was BOOL isOptionPressed = (0 != (flags & NSAlternateKeyMask)); But the zero checking is not necessary to check if a bit mask for equality, unless the bit mask itself represents all zeros in binary. The provided link gives greater detail. )

like image 172
Francis McGrew Avatar answered Nov 09 '22 12:11

Francis McGrew


Francis McGrew's answer needs improvement before it can work, but I still see no solution via that route. The answer as stated does not compile. An actual NSEvent pointer is needed for modifierFlags, which is not a class method as the answer would suggest.

One would hope that the needed event might be obtained by the following.

NSEvent *event = [NSApp currentEvent];

However when called from applicationDidFinishLaunching the resulting event is nil. At least this is true in my testing on Snow Leopard.

applicationDidFinishLaunching has an NSNotification argument but I don't know how to make any use of it.

I found a similar question on cocobuilder.com from 2007 and the answer there is basically to call the carbon function GetCurrentKeyModifiers and convert the carbon flags to cocoa form.

See http://www.cocoabuilder.com/archive/cocoa/176882-detecting-modifier-keys-at-launch.html

like image 1
Kurt Bigler Avatar answered Nov 09 '22 13:11

Kurt Bigler