Nick Moore
Nick Moore

Reputation: 15847

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?

Upvotes: 8

Views: 1955

Answers (2)

iloveitaly
iloveitaly

Reputation: 2155

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())

Upvotes: 5

Zac Bowling
Zac Bowling

Reputation: 6578

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.

Upvotes: 4

Related Questions