代码之家  ›  专栏  ›  技术社区  ›  alexyorke

更改objective-c中的桌面图片

  •  0
  • alexyorke  · 技术社区  · 14 年前

    如何更改cocoa/objective-c中的桌面图片?我试过使用默认值,但有很多错误。

    NSArray *args=[NSArray arrayWithObjects:@"write",@"com.apple.desktop", @"Background", @"'{default = {ImageFilePath = \"~/desktop.jpg\";};}'", nil];
    
    NSTask *deskTask=[[NSTask alloc] init];
    
    [deskTask setArguments: args];
    
    [deskTask setLaunchPath:@"/usr/bin/defaults"];
    [deskTask launch];
    [[NSDistributedNotificationCenter defaultCenter] postNotificationName:@"com.apple.desktop" object:@"BackgroundChanged"];
    

    命令在终端中成功运行。我不需要任何人告诉我 但我想了解一下。

    2 回复  |  直到 14 年前
        1
  •  3
  •   Chuck    14 年前

    我认为规范的方法是对系统事件使用脚本。Applescript版本类似于:

    tell application "System Events"
        tell current desktop
            set picture to (whatever)
        end tell
    end tell
    

    你可以用 Scripting Bridge

        2
  •  2
  •   Peter Hosey    14 年前

    在shell中使用tilde压缩路径时,shell会为您展开tilde,因此在shell中运行命令时,可以将桌面图片路径设置为展开路径(/path/to)/桌面.jpg). 使用NSTask时没有shell,因此显示的代码将其设置为tilde压缩路径。很少有东西期待这样的路径;它们不会扩展tilde,所以它不起作用。

    要使代码正常工作,您需要使用NSString对象的适当方法扩展tilde本身,或者通过附加到 NSHomeDirectory() .

    也就是说,按照Chuck的建议与系统事件对话是实现这一点的更好方法。注意他的评论,告诉你如何做到这一点,而不需要豹。