开发者

Convert Objective-C code to C++ for detecting user idle time on OS X

开发者 https://www.devze.com 2023-01-12 22:18 出处:网络
I\'m developing Qt/C++ application and I need simple function that retrive me User idle time in seconds on Mac OS X.

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.
                    }
  开发者_JS百科              }
                CFRelease(dict);
            }
            IOObjectRelease(entry);
        }
        IOObjectRelease(iter);
    }
    return idlesecs;
}    

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消