views:

106

answers:

1

Hi,

I'm developing Qt/C++ application and I need simple function that retrive me User idle time in seconds on Mac OS X.

I found this code for detection User idle time.

#include <IOKit/IOKitLib.h>

/**
 Returns the number of seconds the machine has been idle or -1 if an error occurs.
 The code is compatible with Tiger/10.4 and later (but not iOS).
 */
int64_t SystemIdleTime(void) {
    int64_t idlesecs = -1;
    io_iterator_t iter = 0;
    if (IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IOHIDSystem"), &iter) == KERN_SUCCESS) {
        io_registry_entry_t entry = IOIteratorNext(iter);
        if (entry) {
            CFMutableDictionaryRef dict = NULL;
            if (IORegistryEntryCreateCFProperties(entry, &dict, kCFAllocatorDefault, 0) == KERN_SUCCESS) {
                CFNumberRef obj = CFDictionaryGetValue(dict, CFSTR("HIDIdleTime"));
                if (obj) {
                    int64_t nanoseconds = 0;
                    if (CFNumberGetValue(obj, kCFNumberSInt64Type, &nanoseconds)) {
                        idlesecs = (nanoseconds >> 30); // Divide by 10^9 to convert from nanoseconds to seconds.
                    }
                }
                CFRelease(dict);
            }
            IOObjectRelease(entry);
        }
        IOObjectRelease(iter);
    }
    return idlesecs;
}    

How to convert this code to C++, to be used with my Qt/C++ project?

+1  A: 

You just need to add IOKit.framework in the list of linked frameworks. Think of a framework as a bundle of shared libraries and associated resources. IOKit.framework is at

 /System/Library/Frameworks/IOKit.framework

I don't know how to do that in a Qt project; the project should have a list of extra frameworks which you want to link against. If it's a standard XCode project, there's a menu entry called add a framework to the project or something like that.

Yuji
Thanks. I use XCode and this was helpful.
Aleksandar