Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine pressed modifier keys when a Cocoa app is started?

In an app I'm developing, a database is used to store all user data, usually located somewhere in Library/Application Support. In order to enable the user to switch the database, I want to implement a functionality similar to iTunes or iPhoto, where the app asks for the library's or database's location if the option key is pressed upon starting the app.

How can I check the currently pressed (modifier) keys if no NSEvent is at hand?

I already tried:

[NSResponder flagsChanged:(NSEvent *)theEvent] – Probably not called because the option key is already down before the window and any responders are instantiated.

[[NSApplication sharedApplication] currentEvent] – Returns nil.

like image 289
C. S. Hammersmith Avatar asked May 12 '15 17:05

C. S. Hammersmith


2 Answers

Swift 5 variant:

func applicationDidFinishLaunch(_ aNotification: Notification?) {

    if NSEvent.modifierFlags.intersection(.deviceIndependentFlagsMask) == .option {
        // Your code
    }

}
like image 129
Ely Avatar answered Oct 19 '22 10:10

Ely


Put this in applicationDidFinishLaunching:

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

if (modifiers == NSAlternateKeyMask)   { 
    // do your stuff here 
}

Beginning with macOS 10.12, this should be:

NSUInteger modifiers = ([NSEvent modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask);

if (modifiers == NSEventModifierFlagOption)   { 
    // do your stuff here 
}
like image 31
Rupert Pupkin Avatar answered Oct 19 '22 11:10

Rupert Pupkin