Windows-Icons in C# nutzen
27.12.2014
Mit den folgenden Methoden lassen sich Icons aus beliebigen DLLs (z.B. shell32.dll) oder EXEn auslesen und in C# nutzen:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
public static ImageSource Extract(string file, int number, bool largeIcon) { IntPtr large; IntPtr small; try { ExtractIconEx(file, number, out large, out small, 1); System.Drawing.Icon img = System.Drawing.Icon.FromHandle(largeIcon ? large : small); System.Drawing.Bitmap bitmap = img.ToBitmap(); IntPtr hBitmap = bitmap.GetHbitmap(); ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); return wpfBitmap; } catch { return null; } } public static System.Drawing.Icon ExtractAsIcon(string file, int number, bool largeIcon) { IntPtr large; IntPtr small; try { ExtractIconEx(file, number, out large, out small, 1); System.Drawing.Icon img = System.Drawing.Icon.FromHandle(largeIcon ? large : small); return img; } catch { return null; } } public static System.Drawing.Bitmap ExtractAsBitmap(string file, int number, bool largeIcon) { IntPtr large; IntPtr small; try { ExtractIconEx(file, number, out large, out small, 1); System.Drawing.Icon img = System.Drawing.Icon.FromHandle(largeIcon ? large : small); return img.ToBitmap(); } catch { return null; } } |
number gibt dabei an das wie vielte Icon es aus der Datei ist. Die Nummerierung beginnt bei 0 und erfolgt (bei Sicht aus dem Explorer) spaltenweise: