【问题标题】:Convert Objective-C code to C++ for detecting user idle time on OS X将 Objective-C 代码转换为 C++ 以检测 OS X 上的用户空闲时间
【发布时间】:2011-04-02 15:12:53
【问题描述】:

我正在开发 Qt/C++ 应用程序,我需要简单的函数来检索我在 Mac OS X 上的用户空闲时间(以秒为单位)。

我找到了这个检测用户空闲时间的代码。

#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;
}    

如何将此代码转换为 C++,以用于我的 Qt/C++ 项目?

【问题讨论】:

  • 有什么问题?这是直接的 C 语言,已经可以在 C++ 项目中使用。
  • 我的链接器有问题:“_IOServiceGetMatchingServices”等符号未找到。它编译没有问题,但不想链接

标签: c++ macos qt operating-system


【解决方案1】:

您只需在链接框架列表中添加IOKit.framework。将框架视为一组共享库和相关资源。 IOKit.framework

 /System/Library/Frameworks/IOKit.framework

我不知道如何在 Qt 项目中做到这一点;该项目应该有一个您要链接的额外框架的列表。 如果它是一个标准的 XCode 项目,则有一个名为 add a framework to the project 或类似名称的菜单条目。

【讨论】:

  • 谢谢。我使用 XCode,这很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多