4
votes

Hi I am new to cocoa programming and would like to know how to create a listener for system wide events (such as mouse drag). I've added this to my app (I saw it on another post):

static CGEventRef eventFunction(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
    printf("event triggered\n");
    return event;
}

But it is never called and im not sure where I am meant to register a call back.

1

1 Answers

7
votes

The easiest way to watch global mouse events is to use the NSEvent class method addGlobalMonitorForEventsMatchingMask:handler:

Example:

[NSEvent addGlobalMonitorForEventsMatchingMask:NSLeftMouseDraggedMask 
                                       handler:^(NSEvent *event) {
    NSLog(@"Dragged...");
}];

Note that this only works in other applications, to get those events in your own app, you have to add an additional local event handler.