tags:

views:

113

answers:

2

I need to add icon of any file I selected during run time.

I have project which provide with button (when press will open dialog allowing you to select which file you need it)

when user select the file (AutoCad , MS Office , etc) I need my project to read belong icon of this file and insert this icon in picturebox..

Same one tell me you can found all icon , which windows used to show 'icon', you can read from registry .. but he does not know where found or is he sure or not.

A: 

I'm assuming you know how to set the Image of a PictureBox, and that it's the actual icon you're looking for.

This will give you the path of the DefaultIcon for a particular program: HKEY_CLASSES_ROOT\<ProgramID>\DefaultIcon

...where ProgramID is essentially the filetype you are opening (e.g.: Excel.AddIn). If you're not sure of the ProgramID you need, you must look under the entry for the extension (.doc, .xls, etc.) in question first, which is also within HKEY_CLASSES_ROOT

Joey
+1  A: 

Hi, You can use the SHGetFileInfo function

try this code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;


namespace WindowsFormsApplication6
{

  public partial class Form1 : Form
  {

[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
  public IntPtr hIcon;
  public IntPtr iIcon;
  public uint dwAttributes;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
  public string szDisplayName;
  [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
  public string szTypeName;
};

class Win32
{
  public const uint SHGFI_ICON = 0x100;
  public const uint SHGFI_LARGEICON = 0x0;    
  public const uint SHGFI_SMALLICON = 0x1;    

  [DllImport("shell32.dll")]
  public static extern IntPtr SHGetFileInfo(string pszPath,
                              uint dwFileAttributes,
                              ref SHFILEINFO psfi,
                              uint cbSizeFileInfo,
                              uint uFlags);
}

    private void button1_Click(object sender, EventArgs e)
    {
      string fName;     
      SHFILEINFO shinfo = new SHFILEINFO();
      OpenFileDialog openFileDialog1 = new OpenFileDialog();
      openFileDialog1.Filter = "All files (*.*)|*.*";
      openFileDialog1.FilterIndex = 2;
      openFileDialog1.RestoreDirectory = true;

      if (openFileDialog1.ShowDialog() == DialogResult.OK)
      {
        fName     = openFileDialog1.FileName;
        Win32.SHGetFileInfo(fName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);
        System.Drawing.Icon myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
        pictureBox1.Image=(Image) myIcon.ToBitmap();
      }

    }


    public Form1()
    {
      InitializeComponent();
    }
  }
}
RRUZ