Search code examples
macosbashstartup

How to check if option key is pressed at startup of a mac bash Application


I got a relatively simple question.

I have a few mac applications that have launchers written in bash. I wanted to add a little feature to the launchers, by letting others access a config.app or something else located in /Contents/Resources, when they press the 'option/alt' key at the startup of the app. Kinda like iTunes or iPhoto, where you can access a little options menu.

I don't know how the code should look like when it's purely in bash; i found a few examples that make use of applescript and/or cocoa hooks, but none purely in bash.

Something like: if 'optionKeyDown'; then open "$WORKDIR/../Resources/config.app"

Or is this not possible in pure bash at all?


Solution

  • There's a good solution here: http://lists.apple.com/archives/applescript-users/2009/Sep/msg00374.html

    Take the following code:

    #import <Carbon/Carbon.h>
    
    int main (int argc, const char * argv[]) {
        unsigned int modifiers = GetCurrentKeyModifiers();
    
        if (argc == 1)
            printf("%d\n", modifiers);
    
        else {
    
            int i, result = 1;
            for (i = 1; i < argc; ++i) {
    
                if (0 == strcmp(argv[i], "shift"))
                    result = result && (modifiers & shiftKey);
    
                else if (0 == strcmp(argv[i], "option"))
                    result = result && (modifiers & optionKey);
    
                else if (0 == strcmp(argv[i], "cmd"))
                    result = result && (modifiers & cmdKey);
    
                else if (0 == strcmp(argv[i], "control"))
                    result = result && (modifiers & controlKey);
    
                else if (0 == strcmp(argv[i], "capslock"))
                    result = result && (modifiers & alphaLock);
    
            }
            printf("%d\n", result);
        }
        return 0;
    }
    

    Paste it into a file called, e.g. keys.m.

    Then build a command line utility like this:

    $ gcc keys.m -framework Carbon -o keys
    

    Put the keys executable somewhere in your path, e.g. /usr/local/bin, or even just in the same directory as your bash script, then you can call it as e.g. keys option and check the returned string for "0" or "1".