Wednesday, March 07, 2007

One of the recent question that came up on the forums on how to extract icon from an exe file in CF. The ExtractIconEx is available on Windows CE platform as well as desktop, so I went to http://www.pinvoke.net/, copied the code from here, removed unneeded 'unsafe' statements and modified the PInvoke declarations to use coredll.dll:

public static Icon ExtractIconFromExe(string file, bool large)

{           

       int readIconCount = 0;

       IntPtr[] hDummy = new IntPtr[1] { IntPtr.Zero };

       IntPtr[] hIconEx = new IntPtr[1] { IntPtr.Zero };

 

       try

       {

          if (large)

               readIconCount = ExtractIconEx(file, 0, hIconEx, hDummy, 1);

          else

               readIconCount = ExtractIconEx(file, 0, hDummy, hIconEx, 1);

 

          if (readIconCount > 0 && hIconEx[0] != IntPtr.Zero)

          {

             // GET FIRST EXTRACTED ICON

             Icon extractedIcon = (Icon)Icon.FromHandle(hIconEx[0]).Clone();

             return extractedIcon;

          }

          else // NO ICONS READ

             return null;

       }

       catch (Exception ex)

       {

           /* EXTRACT ICON ERROR */

           // BUBBLE UP

           throw new ApplicationException("Could not extract icon", ex);

       }

       finally

       {

           // RELEASE RESOURCES

           foreach (IntPtr ptr in hIconEx)

              if (ptr != IntPtr.Zero)

                   DestroyIcon(ptr);

                   foreach (IntPtr ptr in hDummy)

                        if (ptr != IntPtr.Zero)

                            DestroyIcon(ptr);

       }

           

}

 

 

 

[DllImport("coredll.dll")]

static extern int ExtractIconEx(string szFileName, int nIconIndex,

  IntPtr[] phiconLarge, IntPtr[] phiconSmall, uint nIcons);

 

[DllImport("coredll.dll", EntryPoint = "DestroyIcon", SetLastError = true)]

private static  extern int DestroyIcon(IntPtr hIcon);

 

 The followup question was how to display the Icon in the PictureBox, so here it the quick solution for it too:

public Bitmap GetBitmap(Icon icon)

{

     Bitmap bmp = new Bitmap(icon.Width, icon.Height);

     //Create temporary graphics

     Graphics gxMem = Graphics.FromImage(bmp);

     //Draw the icon

     gxMem.DrawIcon(icon, 0, 0);

     //Clean up

     gxMem.Dispose();

     return bmp;

 }

3/7/2007 2:07:09 PM (GMT Standard Time, UTC+00:00)  #    Comments [2]  |