Objective-C OS X系统命令

时间:2013-04-04 10:21:47

标签: objective-c macos cocoa

有没有人知道可以使用Objective-C执行的任何有用的系统命令,下面是一些有用的列表:

  • 启动屏幕保护程序
  • 睡眠
  • 关机
  • 清空垃圾箱
  • 弹出量
  • 打开应用程序
  • 锁定
  • 重新启动
  • 注销

基本上,我想在用户点击NSButton时启动其中一个命令,这样就可以通过这种方式实现一个方法。

1 个答案:

答案 0 :(得分:1)

对于屏幕保护程序:

- (IBAction)screensaver:(id)sender {
    NSString *script=@"tell application \"ScreenSaverEngine\" \
                             \nactivate \
                             \nend tell";
    NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:script];
    [appleScript executeAndReturnError:nil];

}

对于空垃圾:

- (IBAction)emptyTrash:(id)sender {
    NSString *script=@"tell application \"Finder\" \
                             \nempty the trash \
                             \nend tell";
    NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:script];
    [appleScript executeAndReturnError:nil];
}

对于Open Application

使用此

NSString *script=@"tell application \
                   \n\"Name of application\" \
                    \nto activate";

要卸载卷,需要输入大量的AppleScript。以下是:将其作为字符串并传递给NSAppleScript,如上所述:

set diskName to "YourDiskNameHere"
tell application "Finder"
 if disk diskName exists then
  eject disk diskName
 else
  tell current application
   set deviceLine to (do shell script "diskutil list | grep \"" & diskName & "\" | awk '{ print $NF }' }'")
   if deviceLine = "" then
    display dialog "The disk \"" & diskName & "\" cannot be found." buttons {"OK"} default button 1 with title "Error" with icon caution
   end if
   set foundDisks to paragraphs of deviceLine
   repeat with i from 1 to number of items in foundDisks
    set this_item to item i of foundDisks
    if this_item contains "disk" then
     do shell script "diskutil mountDisk /dev/" & this_item
    end if
   end repeat
  end tell
 end if
end tell

restart, shut down, sleep, logout

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]) {
    NSLog([scriptError description]); 
}
相关问题