Assign an icon set (.icns) to a file

As part of my app’s operation, I would like to assign an icon set to a file after it’s created. I can use the MBS “SetIcon” function, but it seems to expect a single picture which it then handles internally before assigning the icon to the file.

@Christian_Schmitz is it possible to handle this with a .icns file, or do I need to create a PNG for the largest (512 @2) and pass that as an NSImageMBS?

You can do this with declares:

Public Function SetIcon(extends f as Folderitem, iconfile as FolderItem) As Boolean
  #if TargetMacOS
    Declare Function NSClassFromString Lib "Foundation" (name as cfstringref) as ptr
    Declare Function alloc Lib "Foundation" selector "alloc" (cls as ptr) as ptr
    // @property(class, readonly, strong) NSWorkspace *sharedWorkspace;
    Declare Function getSharedWorkspace Lib "Foundation" selector "sharedWorkspace" (cls as ptr) as Ptr
    dim sharedWorkspace as ptr = getSharedWorkspace(NSClassFromString("NSWorkspace"))
    // - (instancetype)initByReferencingFile:(NSString *)fileName;
    Declare Function initByReferencingFile_ Lib "Foundation" Selector "initByReferencingFile:" (obj as ptr, fileName as CFStringRef) As Ptr
    dim image as ptr = initByReferencingFile_(alloc(NSClassFromString("NSImage")), iconfile.NativePath)
    // - (BOOL)setIcon:(NSImage *)image forFile:(NSString *)fullPath options:(NSWorkspaceIconCreationOptions)options;
    Declare Function setIcon_forFile_options_ Lib "Foundation" Selector "setIcon:forFile:options:" (obj as ptr, image as Ptr, fullPath as CFStringRef, options as Integer) As Boolean
    return setIcon_forFile_options_(sharedWorkspace, image, f.NativePath, 2) // 2 = exclude quicktime icons
End Function

Well, you may be able to create a NSImage from the icon. Not sure about how.

Or just take the biggest icon from it as PNG.

This is what I ended up doing.

1 Like