20

I've assigned an icon to a C# WinForms app using the Project Properties tab. This icon is supplied along with the program manifest at build time. Is there a way to get an System.Drawing.Icon object of this icon at runtime, without having to embed it in resources again?

I've done my research; There's a way to extract an icon out of an EXE, but nothing I can find to extract the icon off the running C# application from within the application.

Community
  • 1
  • 1
Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607
  • Duplicate question? http://stackoverflow.com/questions/203456/how-can-i-get-the-icon-from-the-executable-file-only-having-an-instance-of-its – Wyatt Earp Aug 20 '14 at 11:28
  • 1
    Not a duplicate. I just linked to a similar question with that SAME function (`Icon.ExtractAssociatedIcon`) specifically saying I DON'T want to do that! – Robin Rodricks Aug 20 '14 at 11:49
  • The icon is embedded as an *unmanaged* resource so that Windows can use it. So you'd have to do the same thing Windows does to get it back and pinvoke LoadImage() to retrieve it. Which is silly, icons are small resources so there's no point in avoiding embedding it as a managed resource as well. – Hans Passant Aug 20 '14 at 12:45

2 Answers2

33

Did you see the second answer in the link? (How can I get the icon from the executable file only having an instance of it's Process in C#)

//Gets the icon associated with the currently executing assembly
//(or pass a different file path and name for a different executable)
Icon appIcon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);

That seems like it's getting the icon for the executing assembly.

Community
  • 1
  • 1
Wyatt Earp
  • 1,783
  • 13
  • 23
  • 4
    It should be noted that this method will throw `System.ArgumentException` if the executing assembly is on a network path. MSDN mentions that but I somehow managed to miss that bit. – bokibeg Feb 06 '17 at 15:30
  • 2
    A note, `Assembly` is in `System.Reflection` – AaA Mar 28 '18 at 07:58
  • 1
    [ExtractIconEx](http://www.pinvoke.net/default.aspx/shell32/ExtractIconEx.html) does the job even if application was loaded from the network path – oleksa Sep 06 '19 at 08:33
  • 3
    If you want to use app executable file icon, you should use Assembly.GetEntryAssembly().Location. – Majid Oct 08 '19 at 08:27
1

Here you can get the icon of the Form itself in case it's what you lookin for:

Bitmap temp = this.Icon.ToBitmap();
temp.Save("c:\\Users\\userName\\Downloads\\icon.png");
karrtojal
  • 796
  • 7
  • 16