Get picture of current application icon

Just for the records:
Define the NSRect struct (x, y, w, h as Single), put the code below in a Canvas Paint event and add your “targetFilePath”:

[code] #pragma Unused areas

dim targetImageSize as Integer = min(g.width, g.height)
const targetFilePath = “/SAMPLE/PATH/SAMPLE_FILE”

declare function NSClassFromString lib “Cocoa” (aClassName as CFStringRef) as Ptr
declare function iconForFile lib “Cocoa” selector “iconForFile:” (obj_id as Ptr, fullPath as CFStringRef) as Ptr
declare function sharedWorkspace lib “Cocoa” selector “sharedWorkspace” (class_id as Ptr) as Ptr
declare sub CGContextDrawImage lib “Cocoa” (context as Ptr, rect as NSRect, image as Ptr)
declare function CGImageForProposedRect lib “Cocoa” selector “CGImageForProposedRect:context:hints:” (obj_id as Ptr, byref proposedDestRect as NSRect, referenceContext as Ptr, hints as Ptr) as Ptr

dim imageRef as MemoryBlock = iconForFile(sharedWorkspace(NSClassFromString(“NSWorkspace”)), targetFilePath)

dim p as new picture(targetImageSize,targetImageSize)
dim rect As NSRect
rect.w = targetImageSize
rect.h = targetImageSize

// Convert the NSImage to CGImage
dim cntx as Ptr =ptr(p.Graphics.Handle(Graphics.HandleTypeCGContextRef))
dim cgPtr as Ptr = CGImageForProposedRect( imageRef, rect, nil, nil)

// Draw the CGImage to our Xojo picture
CGContextDrawImage cntx, rect, cgPtr

g.DrawPicture p, 0, 0
[/code]

With parts based on https://forum.xojo.com/18576-how-to-use-nsimage-for-retina-image-handling and https://forum.xojo.com/13271-nsimage-imagenamed-and-drawing/0 and of course macoslib.

Note: No error checking done here.

1 Like