Extracting executable file icon under SWT

Recently one of my colleagues at work found out that in pure SWT you’re not able to extract icon from an executable file, what you can only do is to get an icon from a file that is associated with specific file type (extension). So, I decided to write a method of my own, and here is it.

public ImageData getExecutableFileIcon(String fileName, boolean large)
{
    int nIconIndex = 0;
    ImageData imageData = null;

    TCHAR lpszFile = new TCHAR(0, fileName, true);
    int /*long*/ [] phiconSmall = new int /*long*/[1];
    int /*long*/ [] phiconLarge = new int /*long*/[1];
    OS.ExtractIconEx(lpszFile, nIconIndex, phiconLarge, phiconSmall, 1);

    if (phiconSmall[0] != 0 && !large)
    {
        Image image = Image.win32_new(null, SWT.ICON, phiconSmall[0]);
        imageData = image.getImageData();
        image.dispose();
    }

    if (phiconLarge[0] != 0 && large)
    {
        Image image = Image.win32_new(null, SWT.ICON, phiconLarge[0]);
        imageData = image.getImageData();
        image.dispose();
    }

    return imageData;
}

At this moment I don’t really know whether we should call OS.ExtractIconEx for both images, or depending on the flag ask for one of them, dunno.

Although, I have a question for Eclipse community, why similar functionality isn’t available in SWT? Or if it is, where to find it?

4 Responses to “Extracting executable file icon under SWT”

  1. Steve said:

    Mar 23, 09 at 13:56

    The problem is that other platforms, such as Linux GTK, don’t keep an icon inside an executable. Therefore, offering portable API to do this in SWT is a problem because it cannot be implemented on all platforms.

    Having said that, it is possible to offer API as a hint and have it fail gracefully on platforms that don’t support it. The trick here is to make sure the failure is graceful. In the case of the “icon for an exe”, is it critical that an application get this? Getting null on platforms that don’t support it (ie non-Windows) is probably ok.

  2. Pascal Rapicault said:

    Mar 23, 09 at 14:04

    If that helps, note that PDE Build has something called a branding iron that allows you to replace the icon inside an exe.

  3. Felipe Heidrich said:

    Mar 25, 09 at 16:54

    Search references to ExtractIconEx in SWT…
    You’ll find Program#getImageData()

  4. Łukasz Milewski said:

    Mar 25, 09 at 17:18

    @Felipe, yes, did that and this is where I’ve placed my own method, unfortunately you can’t create Program object to specific executable file, you can only get Program object that will hold information about application that is associated with specific file type.


Leave a Reply