Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically check whether monitor is switched off

Mac OS X has a power saving feature which allows the OS to turn off the monitor. Is there an API to detect in code whether the monitor is currently switched on or off?

like image 444
Nick Moore Avatar asked Feb 09 '11 16:02

Nick Moore


2 Answers

I used the IORegistryExplorer and checked out the IOPMrootDomain IOSleepSupported value and it registered as true while the monitor was not asleep (which would make sense, but I would guess that the above code would not return the current sleep state of the monitor).

After a bit of searching I found this bit of code that seems to properly return the sleep state of the main monitor

CGDisplayIsAsleep(CGMainDisplayID())
like image 108
iloveitaly Avatar answered Sep 27 '22 18:09

iloveitaly


Check out IOKit's power management section. http://developer.apple.com/library/mac/#documentation/DeviceDrivers/Conceptual/IOKitFundamentals/PowerMgmt/PowerMgmt.html#//apple_ref/doc/uid/TP0000020-TPXREF104

You might be able to use IORegistryExplorer and find a node with state information on the setting you are looking for. There can be multiple monitors on a Mac in different states, so you have to enumerate the tree looking for all the nodes with the class type you need.

Sleep state is handled in IOPMrootDomain.cpp in the Darwin kernel. You can probe it with IOKit I believe. http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/iokit/Kernel/IOPMrootDomain.cpp

Something like:

mach_port_t         masterPort;
io_registry_entry_t     root;
kern_return_t       kr;
boolean_t           flag = false;

kr = IOMasterPort(bootstrap_port,&masterPort);

if ( kIOReturnSuccess == kr ) {
    root = IORegistryEntryFromPath(masterPort,kIOPowerPlane ":/IOPowerConnection/IOPMrootDomain");
    if ( root ) {
        CFTypeRef data;

        data = IORegistryEntryCreateCFProperty(root,CFSTR("IOSleepSupported"),kCFAllocatorDefault,kNilOptions);
        if ( data ) {
            flag = true;
            CFRelease(data);
        }
        IOObjectRelease(root);
    }
}
return flag;

There is a function in IOKit called getPowerState(). Not sure if it's accessible.

Hope that helps.

like image 21
Zac Bowling Avatar answered Sep 27 '22 18:09

Zac Bowling