Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Got .PNG file. Want embeddded icon resource displayed as icon on form title bar

Tags:

c#

.net

winforms

This was an interview question. Given Visual Studio 2008 and an icon saved as a .PNG file, they required the image as an embedded resource and to be used as the icon within the title bar of a form.

I'm looking for what would have been the model answer to this question, Both (working!) code and any Visual Studio tricks. (Model answer is one that should get me the job if I meet it next time around.)

Specifically I don't know how to load the image once it is an embedded resource nor how to get it as the icon for the title bar.

As a part solution, ignoring the embedded bit, I copied the resource to the ouput directory and tried the following:-

public partial class Form1 : Form {     public Form1()     {         InitializeComponent();         this.Icon = new Icon("Resources\\IconImage.png");     } } 

This failed with the error "Argument 'picture' must be a picture that can be used as a Icon."

I presuming that the .PNG file actually needed to be a .ICO, but I couldn't see how to make the conversion. Is this presumption correct or is there a different issue?

like image 579
David Max Avatar asked Sep 30 '08 17:09

David Max


People also ask

How do I add an icon to a resource file?

Just right click on your project-> add-> resource. Add resource window would have popped up where in you can select icon as your preference and select import. Then it lets you to browse through your directory and select your icon.


2 Answers

Fire up VS, start new Windows Application. Open the properties sheet, add the .png file as a resource (in this example: glider.png ). From hereon, you can access the resource as a Bitmap file as WindowsFormsApplication10.Properties.Resources.glider

Code for using it as an application icon:

 public Form1()         {             InitializeComponent();             Bitmap bmp = WindowsFormsApplication10.Properties.Resources.glider;             this.Icon = Icon.FromHandle(bmp.GetHicon());         } 
like image 77
Silver Dragon Avatar answered Sep 22 '22 20:09

Silver Dragon


Icon.FromHandle will cause problems with a PNG, because PNGs have more than one bit of transparency. This type of issue can be solved with a library like IconLib.

Chances are they didn't know how to do it and they were trying to squeeze the answer out of potential employees. Furthermore, setting the icon of the form from a PNG is an unnecessary performance hit, it should have been an ICO in the first place.

like image 38
Jonathan C Dickinson Avatar answered Sep 20 '22 20:09

Jonathan C Dickinson