How can I load a program icon in C#

2019-09-10 15:55发布

问题:

I have a path of some program (for example explorer), how can I get program icon, convert it to png/jpeg and then display in PictureBox?

I have something like this:

string filePath = "C:\\myfile.exe";
Icon TheIcon = IconFromFilePath(filePath);
if (TheIcon != null) {

 // But then I don't know what to do...

}

public Icon IconFromFilePath(string filePath){
 Icon programicon = null;
 try {
  programicon = Icon.ExtractAssociatedIcon(filePath);
 }
 catch { } 
 return programicon;
}

I found something similar here. Here is the icon. How I can create 32-bit icon?

回答1:

The code is surprisingly simple if you know where to look. Start with the Icon class, since that's fundamentally what you're after here.

If you browse its methods, you'll come across a very interesting looking ExtractAssociatedIcon. That accepts a single string parameter that specifies the path to a file containing an icon, such as an executable file.

So that gives you an Icon object, now you just need to display it in a PictureBox. You don't have to convert it to a PNG or JPEG, a bitmap works fine. And there's a built-in member function for that: ToBitmap.

Assigning the new bitmap to the PictureBox.Image property is all you need to do to display it.



标签: c# icons