我尝试使用 Application Scripting Bridge 让我的 Mac 进入睡眠状态。代码如下所示:
#import "Finder.h"
FinderApplication *Finder = [SBApplication applicationWithBundleIdentifier:@"com.apple.finder"];
[Finder sleep];
但它不起作用。任何想法为什么它不起作用?没有编译错误或警告,但它不起作用……</p>
我尝试使用 Application Scripting Bridge 让我的 Mac 进入睡眠状态。代码如下所示:
#import "Finder.h"
FinderApplication *Finder = [SBApplication applicationWithBundleIdentifier:@"com.apple.finder"];
[Finder sleep];
但它不起作用。任何想法为什么它不起作用?没有编译错误或警告,但它不起作用……</p>
正如我在这个答案中发布的那样,我已经使用以下代码超过 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;
}
请注意,上面的代码是基于来自Technical Q&A QA1134的代码,但我的代码被重新设计为使用AESendMessage()
而不是AESend()
. AESend()
is in HIToolbox.framework
,它在其中,Carbon.framework
因此对于 64 位应用程序不可用。(AESendMessage()
是AE.framework
in的一部分CoreServices
)。
如果 Scripting Bridge 不足以做一些非应用程序特定的事情,比如关闭 Mac,那么您可以转移到 Applescript(以及扩展的 Scripting Bridge)无法直接访问的其他框架。有关关闭 Mac 的信息,请参阅核心服务:技术问答 QA1134:以编程方式导致重新启动、关闭和/或注销