Question

I've searched here and not found any question that really covers this.

I have a cross-platform Windows-OS/X application in which I'd like to be able to detect whether modifier keys like shift or control are being held down while the application starts up.

We'd like to do this to allow the application to start up without reading its preferences file, in case that somehow gets corrupted (we saw in testing a prefs bug, now fixed, that made the window size 0 by 0, for example).

We're using the excellent and comprehensive cross-platform C++ library named Juce. Unfortunately, Juce's master tells me that he believes this is impossible on OS/X at least since you only get keyboard events and there is no way to read the state of the keys unless something changes.

Is this true? Or is there some way around this? I'm almost sure I've used Mac programs that used this mechanism to bypass their preferences.

Or... stepping up one level... is there another solution to providing the functionality of "run the program but don't read the prefs file" other than "holding a key down while launching the program"? This is consumer software so we can't expect too much from the user.

The final solution will end up being a cross-platform one so hints on the Windows side will also be appreciated.

Thanks, and be well! I'll report in with progress on my end.

Was it helpful?

Solution

Works on Mac (Objective-C):

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    NSUInteger theFlags = [NSEvent modifierFlags] & NSDeviceIndependentModifierFlagsMask;

    if(theFlags & NSShiftKeyMask)     NSLog(@"Shift down!");
    if(theFlags & NSControlKeyMask)   NSLog(@"Control down!");
    if(theFlags & NSCommandKeyMask)   NSLog(@"Command down!");
    if(theFlags & NSAlternateKeyMask) NSLog(@"Alternate down!");
    if(theFlags & NSFunctionKeyMask)  NSLog(@"Function down!");

}

OTHER TIPS

The first answer is fine, but in case for some reason you'd like to avoid Objective-C, you can use the Carbon framework:

UInt32 flags = GetCurrentKeyModifiers();
if ( (flags & optionKey) != 0)
{...}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top