views:

1658

answers:

1

In a .NET 1.0 C# application, I wish to display a list of files and folders in a listview control. I want to programmatically retrieve from windows the icons for the files or folders to display them appropriately in the list view.

At present, I am using the Windows API Shell32.dll, but am having problems with the alpha channel in the icons (the backgrounds of the icons are showing up as black, rather than white / transparent).

Below are two code extracts showing the API I'm trying to use, and the implemented code to retrieve the system icon for a folder (the code for the file is similar).

 [DllImport("Shell32.dll")]
 public static extern IntPtr SHGetFileInfo(
  string pszPath,
  uint dwFileAttributes,
  ref SHFILEINFO psfi,
  uint cbFileInfo,
  uint uFlags
  );

... (note : Shell32 is a wrapper class for the above API)

// Get the folder icon
      Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
      Shell32.SHGetFileInfo( null, 
       Shell32.FILE_ATTRIBUTE_DIRECTORY, 
       ref shfi, 
       (uint) System.Runtime.InteropServices.Marshal.SizeOf(shfi), 
       flags );

      System.Drawing.Icon.FromHandle(shfi.hIcon); // Load from the handle

      // Get the icon for storage in an imagelist //
      System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();

Is this the right approach?

Is there a better way to accomplish this?

Or, is there something I need to do to correctly set the alpha channel in the icon?

+2  A: 

There is a bug in .NET 1.x, documented (sort of) in KB822488, whereby alpha channels in icons are lost during conversion into an Image (as would happen when loading them into an ImageList). Unfortunately, the workaround in the article is not particularly helpful for ListViews.

You may be able to use the Windows API to directly load the icons into the list view's image list, bypassing the faulty .NET code. This article discusses getting icons from the System Image List and loading them into a ListView via the Windows API, so you might be able to derive what you need from there.

Eric Rosenberger
Thanks! This has saved me a lot of time.
Jayden