How can I execute a simple Applescript from a C++ program?

↘锁芯ラ 提交于 2019-12-12 08:14:07

问题


I would like to execute the Applescript command tell application "Finder" to open POSIX file */path/to/somefilename* from a C++ program. It looks like I might want to use OSACompileExecute, but I haven't been able to find an example of how to use it. I keep finding examples of how to use the OSACompile Terminal command. Can someone provide an example or a link to an example?


回答1:


Ok, the trick was to not bother trying to compile and execute the Applescript but to simply use the osascript system command:

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

path and file are both char[] variables.

I got the clue from this excerpt from Applescript: The Definitive Guide.




回答2:


Here's an example C function for reading a Get Info comment from the finder using AppleScript.

You could modify it for what you want.

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;


来源:https://stackoverflow.com/questions/9101450/how-can-i-execute-a-simple-applescript-from-a-c-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!