执行某些系统事件,Mac OS X

| 我想要 关掉 重新开始 注销 睡觉 通过正在创建的应用程序,我的系统似乎找不到任何本机的Objective C方法,而且这真的很困难。 任何人都可以指导我执行此操作的最佳方法: 我试过了:
NSString *scriptAction = @\"restart\"; // @\"restart\"/@\"shut down\"/@\"sleep\"/@\"log out\"
NSString *scriptSource = [NSString stringWithFormat:@\"tell application \\\"Finder\\\" to %@\", scriptAction];
NSAppleScript *appleScript = [[[NSAppleScript alloc] initWithSource:scriptSource] autorelease];
NSDictionary *errDict = nil;
if (![appleScript executeAndReturnError:&errDict]) {
    //
}
根本没有运气,也尝试过:
NSAppleScript* theScript = [[NSAppleScript alloc] initWithSource:
                            @\"Tell application \\\"Finder\\\" to restart\"];
if (theScript != NULL)
{
    NSDictionary* errDict = NULL;
    // execution of the following line ends with EXC
    if (YES == [theScript compileAndReturnError: &errDict])
    {
        [theScript executeAndReturnError: &errDict];
    }
    [theScript release];
}
没有运气     
已邀请:
我使用以下代码已有8年以上,没有任何问题: MDRestartShutdownLogout.h:
#import <CoreServices/CoreServices.h>
/*
    *    kAERestart        will cause system to restart
    *    kAEShutDown       will cause system to shutdown
    *    kAEReallyLogout   will cause system to logout
    *    kAESleep          will cause system to sleep
 */
extern OSStatus MDSendAppleEventToSystemProcess(AEEventID eventToSend);
MDRestartShutdownLogout.m:
#import \"MDRestartShutdownLogout.h\"

OSStatus MDSendAppleEventToSystemProcess(AEEventID eventToSendID) {
    AEAddressDesc targetDesc;
    static const ProcessSerialNumber kPSNOfSystemProcess = {0, kSystemProcess };
    AppleEvent eventReply = {typeNull, NULL};
    AppleEvent eventToSend = {typeNull, NULL};

    OSStatus status = AECreateDesc(typeProcessSerialNumber,
         &kPSNOfSystemProcess, sizeof(kPSNOfSystemProcess), &targetDesc);

    if (status != noErr) return status;

    status = AECreateAppleEvent(kCoreEventClass, eventToSendID,
          &targetDesc, kAutoGenerateReturnID, kAnyTransactionID, &eventToSend);

    AEDisposeDesc(&targetDesc);

    if (status != noErr) return status;

    status = AESendMessage(&eventToSend, &eventReply,
                          kAENormalPriority, kAEDefaultTimeout);

    AEDisposeDesc(&eventToSend);
    if (status != noErr) return status;
    AEDisposeDesc(&eventReply);
    return status;
}
请注意,以上代码是基于技术问答QA1134的代码,但是我的代码经过重新设计,使用
AESendMessage()
而不是
AESend()
AESend()
HIToolbox.framework
中,而is8在in8ѭ中,因此不适用于64位应用程序。 (
AESendMessage()
CoreServices
AE.framework
的一部分)。     
如果您从GUI会话登录,那绝对可以。 如果您仅通过
ssh
会话等进行登录,而没有GUI,它将无法正常工作。 请更全面地描述您的情况,遇到的错误等。否则我们将无法为您提供帮助。     

要回复问题请先登录注册