我尝试使用Application Scripting Bridge将我的Mac发送到睡眠状态。 代码如下所示:
#import "Finder.h"
FinderApplication *Finder = [SBApplication applicationWithBundleIdentifier:@"com.apple.finder"];
[Finder sleep];
但它不起作用。任何想法为什么它不起作用?没有编译错误或警告,但它不起作用......
答案 0 :(得分:2)
当我在this answer发布时,我已经使用以下代码超过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()
位于HIToolbox.framework
,位于Carbon.framework
,因此64位应用无法使用。 (AESendMessage()
是AE.framework
)中CoreServices
的一部分。
答案 1 :(得分:0)
如果Scripting Bridge不足以执行非特定于应用程序的操作,例如关闭Mac,那么您可以轻松转移到其他框架,Applescript(以及扩展的Scripting Bridge)无法直接访问。要关闭Mac,请参阅核心服务:Technical Q&A QA1134: Programmatically causing restart, shutdown and/or logout