【问题标题】:How can I execute a simple Applescript from a C++ program?如何从 C++ 程序执行简单的 Applescript?
【发布时间】:2012-02-01 18:48:58
【问题描述】:

我想从 C++ 程序执行 Applescript 命令tell application "Finder" to open POSIX file */path/to/somefilename*。看起来我可能想使用OSACompileExecute,但我找不到如何使用它的示例。我一直在寻找有关如何使用 OSACompile 终端命令的示例。有人可以提供示例或示例链接吗?

【问题讨论】:

    标签: c++ macos applescript appleevents


    【解决方案1】:

    好的,诀窍是不要费心尝试编译和执行 Applescript,而只需使用 osascript 系统命令:

        sprintf(cmd, "osascript -e 'tell app \"Finder\" to open POSIX file \"%s/%s\"'", getcwd(path, MAXPATHLEN), file);
        system(cmd);
    

    path 和 file 都是 char[] 变量。

    我从 Applescript: The Definitive Guide 中的 this excerpt 得到了线索。

    【讨论】:

      【解决方案2】:

      这是一个示例 C 函数,用于使用 AppleScript 从 finder 读取 Get Info 注释。

      你可以根据需要修改它。

      NSString * readFinderCommentsForFile(NSString * theFile){
      /* Need to use AppleScript to read or write Finder Get Info Comments */
      
      /* Convert POSIX file path to hfs path */
      NSURL * urlWithPOSIXPath = [NSURL fileURLWithPath:theFile];
      NSString * hfsStylePathString = 
      (__bridge_transfer NSString    *)CFURLCopyFileSystemPath((__bridge CFURLRef)  urlWithPOSIXPath, kCFURLHFSPathStyle);
      
      /* Build an AppleScript string */
      NSString *appleScriptString = @"tell application \"Finder\"\r get comment of file ";
      appleScriptString = [appleScriptString stringByAppendingString:@"\""];
      appleScriptString = [appleScriptString stringByAppendingString:hfsStylePathString];
      appleScriptString = [appleScriptString stringByAppendingString:@"\""];
      appleScriptString = [appleScriptString stringByAppendingString:@"\r end tell\r"];
      
      
      NSString *finderComment;
      
      NSAppleScript *theScript = [[NSAppleScript alloc] initWithSource:appleScriptString];
      
      NSDictionary *theError = nil;
      finderComment = [[theScript executeAndReturnError: &theError] stringValue];
      NSLog(@"Finder comment is %@.\n", finderComment);
      
      
      return finderComment;
      

      【讨论】:

      • 这是使用 NSAppleScript 对象的 Objective-C 代码示例,不能在 C++ 中使用
      • 对于这个项目,我希望尽可能避免使用 Cocoa 和 Objective-C。
      • 可能objective-c as c 不使用[、]、@ 或: 在这里展示的方式。
      • 这是一个使用 Objective-C 方法的 C 函数。
      • 尝试通过 vanilla c 编译器运行它。这只是 不是 c 语法。
      猜你喜欢
      • 2011-04-12
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2013-03-05
      相关资源
      最近更新 更多