Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically put a Mac into sleep

I can't find any instructions how to put a Mac programmatically into sleep mode (in Objective-C). I'm sure it should be only one line, but could you give me a hint?

like image 249
tamasgal Avatar asked Jun 05 '11 13:06

tamasgal


People also ask

How do I put the Mac to sleep in CMD?

Option–Command–Power button* or Option–Command–Media Eject : Put your Mac to sleep. Control–Shift–Power button* or Control–Shift–Media Eject : Put your displays to sleep.

Can you put Mac on sleep timer?

To enable it and create a schedule, go to System Preferences > Energy Saver and click Schedule... in the lower right corner of the window. There you can set a time and day (weekends or weekdays, too) that the Mac will start up or wake, as well as a time and day(s) when it will restart, shut down or sleep.


1 Answers

#include <stdio.h> 
#include <CoreServices/CoreServices.h>
#include <Carbon/Carbon.h>

SendAppleEventToSystemProcess(kAESleep);

OSStatus SendAppleEventToSystemProcess(AEEventID EventToSend)
{
    AEAddressDesc targetDesc;
    static const ProcessSerialNumber kPSNOfSystemProcess = { 0, kSystemProcess };
    AppleEvent eventReply = {typeNull, NULL};
    AppleEvent appleEventToSend = {typeNull, NULL};

    OSStatus error = noErr;

    error = AECreateDesc(typeProcessSerialNumber, &kPSNOfSystemProcess, 
                                            sizeof(kPSNOfSystemProcess), &targetDesc);

    if (error != noErr)
    {
        return(error);
    }

    error = AECreateAppleEvent(kCoreEventClass, EventToSend, &targetDesc, 
                   kAutoGenerateReturnID, kAnyTransactionID, &appleEventToSend);

    AEDisposeDesc(&targetDesc);
    if (error != noErr)
    {
        return(error);
    }

    error = AESend(&appleEventToSend, &eventReply, kAENoReply, 
                  kAENormalPriority, kAEDefaultTimeout, NULL, NULL);

    AEDisposeDesc(&appleEventToSend);
    if (error != noErr)
    {
        return(error);
    }

    AEDisposeDesc(&eventReply);

    return(error); 
}

More detail on https://developer.apple.com/library/content/qa/qa1134/_index.html

like image 176
Chanok Avatar answered Oct 05 '22 22:10

Chanok