C#类似windows资源管理器-获取文件图标

在做文件管理器的过程中,有一个非常重要的功能实现,就是对不同的文件类型获取文件的描述信息,以及对文件图标的获取

实现这个功能需要调用Windows API,以及对注册表的操作(代码是看了一些网上写的后根据自己的理解写了一个比较简洁易懂的代码)

下面看代码:

 

//根据扩展名获取图标  
public int fileExtIcon(string typeExt, FileInfo f)  
{  
    if (!extIcon.ContainsKey(typeExt) && typeExt != ".exe")  
    {  
        RegistryKey regRead = Registry.ClassesRoot.OpenSubKey(typeExt);  
        if (regRead == null) { return 0; }  
        string subKey = regRead.GetValue("").ToString();  
        RegistryKey regRead1 = Registry.ClassesRoot.OpenSubKey(subKey);  
        if (regRead1 == null) { return 0; }  
        RegistryKey subKey1 = regRead1.OpenSubKey("DefaultIcon");  
        string defaultIcon = subKey1.GetValue("").ToString();  
        string[] defIcon = defaultIcon.Split(',');  
        Icon ic = getExtractIcon(defIcon[0], int.Parse(defIcon[1]));  
        TreeImageList.Images.Add(ic);  
        extIcon.Add(typeExt, i++);  
        return 0;  
    }  
    else if (typeExt == ".exe")  
    {  
        string fullPath = f.FullName;  
        Icon ic = getExtractIcon(fullPath,0);  
        if (ic != null)  
        {  
            TreeImageList.Images.Add(ic);  
            extIcon.Add(typeExt, i++);  
        }  
    }  
    return 0;  
}  

 


这里需要引用windows API

 

 

//获取系统图标  
[DllImport("shell32.dll")]  
public static extern int ExtractIcon(IntPtr h, string strx, int ii);  
public Icon getExtractIcon(string fileName,int iIndex)  
{  
    try  
    {  
        IntPtr hIcon = (IntPtr)ExtractIcon(this.Handle, fileName, iIndex);  
        if (hIcon != IntPtr.Zero)  
        {  
            Icon icon = Icon.FromHandle(hIcon);  
            return icon;  
        }  
    }  
    catch(Exception e)  
    {  
        MessageBox.Show(e.Message,"错误提示",0,MessageBoxIcon.Error);  
    }  
    return null;  
}  

 

 

还有一个问题没解决,文件盒文件夹的图标显示不清晰,我不知道是不是ListView的原因

请各位指点


有问题或建议请联系563921891@qq.com

posted @ 2014-11-26 17:25  GavinQiu  阅读(1579)  评论(0编辑  收藏  举报