2

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 option '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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
spd
  • 2,114
  • 1
  • 29
  • 54

3 Answers3

1

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.

Ross Carter
  • 552
  • 4
  • 12
1

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

Community
  • 1
  • 1
Guillaume
  • 21,685
  • 6
  • 63
  • 95
0

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);
Tim
  • 1,659
  • 1
  • 21
  • 33