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

前端 未结 5 1892
旧时难觅i
旧时难觅i 2021-02-09 06:03

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

5条回答
  •  我在风中等你
    2021-02-09 06:45

    I've found a solution that uses the HID manager, this seems to be the way to do it in Cocoa. (There's another solution for Carbon, but it doesn't work for 64bit OS X.)

    Citing Daniel Reese on the Dan and Cheryl's Place blog:

    #include 
    
    /*
     Returns the number of seconds the machine has been idle or -1 on error.
     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;
                kern_return_t status;
                status = IORegistryEntryCreateCFProperties(entry,
                                                           &dict,
                                                           kCFAllocatorDefault, 0);
                if (status == KERN_SUCCESS)
                {
                    CFNumberRef obj = CFDictionaryGetValue(dict,
                                                           CFSTR("HIDIdleTime"));
                    if (obj) {
                        int64_t nanoseconds = 0;
                        if (CFNumberGetValue(obj,
                                             kCFNumberSInt64Type,
                                             &nanoseconds))
                        {
                            // Convert from nanoseconds to seconds.
                            idlesecs = (nanoseconds >> 30);
                        }
                    }
                    CFRelease(dict);
                }
                IOObjectRelease(entry);
            }
            IOObjectRelease(iter);
        }
        return idlesecs;
    }
    

    The code has been slightly modified, to make it fit into the 80-character limit of stackoverflow.

提交回复
热议问题