简体   繁体   中英

Detect user activity in Cocoa app (taps, clicks, …)

For a Mac application, I want to detect user activity in the app, so I can periodically let a web service know that the user is still active on the endpoint.

In Cocoa Touch, I would override sendEvent of UIApplication , but the sendEvent in NSApplication equivalent in Cocoa, doesn't do the same.

Which APIs should I use instead for a Mac application, to detect user activity? Can I perhaps somehow have a global responder hookup from where I can send the pings to my service?

Preferably, I want to listen for actions the user can be expected to perform every 15-30 second, ie. clicks, tabs, typing, switching windows or applications.

You most likely want to create a global event monitor using +[NSEvent addGlobalMonitorForEventsMatchingMask:handler:] . This calls your handler whenever an event whose type matches the passed mask (you should use NSAnyEventMask ) is sent to another application. You can observe, but not change, the event here, which suits your usage perfectly. There is one thing to watch out for: the documentation says that you won't receive key events unless your app is trusted for Accessibility.

You can do similarly for events that are routed to your own application with +[NSEvent addLocalMonitorForEventsMatchingMask:handler:] .

这不是通知,但是您可以使用CGEventSourceSecondsSinceLastEventType(kCGEventSourceStateCombinedSessionState, kCGAnyInputEventType)查询自用户活动以来的时间。

This worked for me:

-(void) addMyApplicationEventsMonitor {
    self.localEventsMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskAny handler:^NSEvent * (NSEvent *  event) {
        // do your stuff here
        return event;
    }];
}

-(void)dealloc{
    //remember add this to remove your monitor
    [NSEvent removeMonitor:self.localEventsMonitor];
}

reference here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM