Friday, July 30, 2010

Trapping Global Keyboard Events Using Carbon

I came across the question "How do I trap keyboard events in kernel space", I answered this question with a question, why do you need to trap keyboard events in kernel space?...You don't, most of the time. The person then proceeded to tell me he didn't want to have to deal with a Graphical User Interface (gui) and so I thought ok i'll just google "trap key events without a gui mac os x" for him since he probably just skipped that part. Turns out there isn't a guide on creating an application that traps global keyboard events without using a graphical user interface. However it is very possible so I decided to write one.
since this is for tutorial purposes assume that all of this is in main.m (or .c) , also this will only compile properly under an i386 architecture because carbon event loops aren't support by 64 bit archs yet...go figure.
Post a comment with any questions


// *This code is meant to be for tutorial purposes*





#import <Carbon/Carbon.h>
//our callback for the event this is called every time 'your' event happens
OSStatus keyHandler(EventHandlerCallRef nextHandler, EventRef anEvent, void *userData){
printf("Hey! I trapped a global key event\n");
return noErr;
}
//register interest in the events you would like to receive notifications about
void setupEventHandler(){
EventHotKeyRef hotKeyRef;
EventHotKeyID hotKeyID;
EventTypeSpec eventType;
eventType.eventClass = kEventClassKeyboard;
eventType.eventKind = kEventHotKeyPressed;
InstallEventHandler(GetApplicationEventTarget(),
                                            &keyHandler,
                                                      1,
                                             &eventType,
                                                   NULL,
                                                   NULL);
hotKeyID.signature = '1';
hotKeyID.id = 1;
        RegisterEventHotKey(123,
                      optionKey,
                       hotKeyID,
     GetApplicationEventTarget(),
                               0,
                     &hotKeyRef);
}

int main (int argc, const char * argv[]) {
setupEventHandler();
RunApplicationEventLoop();
    
return 0;
}



2 comments:

  1. Still, seems pretty useless. The only time I can think you'd need this is if you were writing a low-level exception handler script in CalaBaza. Can you explain the "gui" part though?

    ReplyDelete
  2. GUI = Graphical User Interface, the usual way of trapping events is by having an 'event capturing method' in a class thats gui object has first responder rights. This is a way to write a global key trapper without using a gui

    ReplyDelete