开发者

Cocoa API to set the default app for a file to open with

开发者 https://www.devze.com 2023-02-03 15:03 出处:网络
Is there any Cocoa or Carbon API to set the default app to open with for a file? i.e If I select a file and do Cmd+i, we get an opt开发者_运维问答ion \'Open With\'. Here we can set the default app to

Is there any Cocoa or Carbon API to set the default app to open with for a file? i.e If I select a file and do Cmd+i, we get an opt开发者_运维问答ion 'Open With'. Here we can set the default app to open a file. Also, there is an option to apply this for all such files.

How do I achieve both of these programmatically?


The API for setting the app on a per-file basis is private. For setting the application that handles a file type, see LSSetDefaultRoleHandlerForContentType and other methods in Launch Services Reference.


To set the default application for a file extension (or file UTI), see my answer here: https://stackoverflow.com/a/8645445/272342


There is a Carbon API to achieve this, see the Resource Manager Reference. You have to create a resource fork for the file you want to open with a specific application and add a resource like this (very quick and dirty code):

FSRef theFsRef;
CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
CFURLGetFSRef(url, &theFsRef);
HFSUniStr255 fork = {0,{0}};
FSGetResourceForkName(&fork);
Handle theResHandle;
ResFileRefNum theRefFile;
ResType rType = 'usro';
ResID rID = 0;
NSMutableData *aData = [[NSMutableData alloc] init];
Byte buf[4] = {0x1A, 0x00, 0x00, 0x00};
[aData appendData:[NSData dataWithBytes:&buf length:sizeof(buf)]];
NSData *bData = [@"/Applications/Firefox.app" dataUsingEncoding:NSUTF8StringEncoding];
[aData appendData:bData];
int len = 4 + [bData length];
[aData appendData:[NSMutableData dataWithLength:(1028-len)]];
PtrToHand ([aData bytes], &theResHandle, [aData length]);
FSCreateResourceFork(&theFsRef,fork.length,fork.unicode,0);
FSOpenResourceFile(&theFsRef,fork.length,fork.unicode,fsRdWrPerm,&theRefFile);
AddResource(theResHandle, rType, rID, "\p");
WriteResource(theResHandle);
ReleaseResource(theResHandle);
UpdateResFile(theRefFile);
CloseResFile(theRefFile);
0

精彩评论

暂无评论...
验证码 换一张
取 消