1

I have the following C# code to extract an icon with a specific index from a specific DLL:

using System;
using System.Drawing;
using System.Runtime.InteropServices;

public class ExtractIcon
{
    public static Icon Extract(string file, int number, bool largeIcon)
    {
        IntPtr large;
        IntPtr small;
        ExtractIconEx(file, number, out large, out small, 1);
        try
        {
            return Icon.FromHandle(largeIcon ? large : small);
        }
        catch
        {
            return null;
        }

    }
    [DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);
}

This works fine. Sort of. Because it doesn't handle transparency.

Take a look:

enter image description here

How can I fix this?


EDIT

Credits to @rbmm

The problem was not the code above but rather the code I was using to convert from Icon to Bitmap. I was using Bitmap.FromHIcon, which apparently discards the transparency. I now use a custom method to convert between these two and it works flawlessly.

Jonas Kohl
  • 1,018
  • 1
  • 11
  • 28
  • may be task not in `ExtractIconEx` but in how you than use icon ? how you draw it ? – RbMm Mar 18 '18 at 15:03
  • @RbMm I draw it to a PictureBox using `Bitmap.FromHicon(Icon.Handle);` – Jonas Kohl Mar 18 '18 at 15:04
  • why you draw it not as icon but as bitmap, which already lost icon mask (icon is 2 bitmaps) – RbMm Mar 18 '18 at 15:06
  • @RbMm That's were the problem was! I now use different code to convert from icon to bitmap and it works fine now. Thanks! – Jonas Kohl Mar 18 '18 at 15:08
  • 2
    I suggest to remove the "Edit" section as it is just confusing. Update original code to include the `Bitmap.FromHIcon` call. Add an actual answer to include the solution (not just a link). This would greatly improve this QA for future readers. – zett42 Mar 18 '18 at 17:30

0 Answers0