从文件路径获取该文件的图标

.Net技术 码拜 10年前 (2014-09-23) 2000次浏览 0个评论

C#获取从指定的文件路径,获取该文件的图标,然后显示在image里。方法总结:

(1)

[DllImport(“shell32.DLL”, EntryPoint = “ExtractAssociatedIcon”)]
private static extern int ExtractAssociatedIconA(int hInst, string lpIconPath, ref int lpiIcon); //声明函数
System.IntPtr thisHandle;
public System.Drawing.Icon SetIcon(string path)
{
int RefInt = 0;
thisHandle = new IntPtr(ExtractAssociatedIconA(0,path, ref RefInt));
return System.Drawing.Icon.FromHandle(thisHandle);
}

(2)

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

namespace WindowsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}
using (Graphics g = this.pictureBox1.CreateGraphics())
{
g.Clear(this.pictureBox1.BackColor); //清除picturebox的背景色,为了画透明图标

g.DrawIcon(GetIcon(this.textBox1.Text, true), 1, 1); //绘制小图标
}
}
static Icon GetIcon(string fileName, bool isLargeIcon)
{
SHFILEINFO shfi = new SHFILEINFO();
IntPtr hI;

if (isLargeIcon)
hI = NativeMethods.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_LARGEICON);
else
hI = NativeMethods.SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), NativeMethods.SHGFI_ICON | NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_SMALLICON);

Icon icon = Icon.FromHandle(shfi.hIcon).Clone() as Icon;

NativeMethods.DestroyIcon(shfi.hIcon); //释放资源
return icon;
}
class NativeMethods
{

[DllImport(“Shell32.dll”, EntryPoint = “SHGetFileInfo”, SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);

[DllImport(“User32.dll”, EntryPoint = “DestroyIcon”)]
public static extern int DestroyIcon(IntPtr hIcon);

public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; //大图标 32×32
public const uint SHGFI_SMALLICON = 0x1; //小图标 16×16
public const uint SHGFI_USEFILEATTRIBUTES = 0x10;
}
}
}

(3)

Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(path);
Image image = icon.ToBitmap();
pix.image=image

目前已通过最简单的第三种方式实现。其他暂未测试。


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明从文件路径获取该文件的图标
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!