Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to know if application is inactive in cocoa mac OSX?

So, i am building a program that will stand on a exhibition for public usage, and i got a task to make a inactive state for it. Just display some random videos from a folder on the screen, like a screensaver but in the application.

So what is the best and proper way of checking if the user is inactive?

What i am thinking about is some kind of global timer that gets reset on every user input and if it reaches lets say 1 minute it goes into inactive mode. Are there any better ways?

like image 208
tobros91 Avatar asked Feb 18 '11 09:02

tobros91


2 Answers

You can use CGEventSourceSecondsSinceLastEventType

Returns the elapsed time since the last event for a Quartz event source.

/*
 To get the elapsed time since the previous input event—keyboard, mouse, or tablet—specify kCGAnyInputEventType.
 */
- (CFTimeInterval)systemIdleTime
{       
    CFTimeInterval timeSinceLastEvent = CGEventSourceSecondsSinceLastEventType(kCGEventSourceStateHIDSystemState, kCGAnyInputEventType);
    return timeSinceLastEvent;
}
like image 156
Parag Bafna Avatar answered Oct 22 '22 03:10

Parag Bafna


I'm expanding on Parag Bafna's answer. In Qt you can do

#include <ApplicationServices/ApplicationServices.h>

double MyClass::getIdleTime() {
    CFTimeInterval timeSinceLastEvent = CGEventSourceSecondsSinceLastEventType(kCGEventSourceStateHIDSystemState, kCGAnyInputEventType);
    return timeSinceLastEvent;
}

You also have to add the framework to your .pro file:

QMAKE_LFLAGS += -F/System/Library/Frameworks/ApplicationServices.framework
LIBS += -framework ApplicationServices

The documentation of the function is here

like image 22
Michael Franzl Avatar answered Oct 22 '22 01:10

Michael Franzl