在Winform开发中,大家普遍利用Listview来显示文件列表。 但是Listview本身并不具备显示当前系统图标的功能。所以要想实现类似的功能,需要利用Icon和Imagelist来辅助。
1, 实例一个imagelist作为图标管理容器。
2, 根据文件绝对路径将对应的系统图标加入imagelist
3, 将listview的显示属性View修改为:SmallIcon
4, 获取对应图标的index 并赋值给ListViewItem
源代码如下:
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ListViewDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
string DemoFolder = "c:\\listview";
DirectoryInfo di = new DirectoryInfo(DemoFolder);
//get all fileinfo in the demo folder
foreach (FileInfo f in di.GetFiles())
{
//add system icon of current file into imagelist
if (!imageList1.Images.Keys.Contains(f.Extension))
{
imageList1.Images.Add(f.Extension, Icon.ExtractAssociatedIcon(f.FullName));
}
ListViewItem lvi = new ListViewItem();
lvi.Text = f.Name;
//get imageindex from imagelist according to the file extension
lvi.ImageIndex = imageList1.Images.Keys.IndexOf(f.Extension);
listView1.Items.Add(lvi);
}
}
}
}
效果图:
对于一些非当前系统中的文件,如果没有文件绝对路径,只知道文件扩展名,就需要再添加一个自定义的类。 根据文件扩展名来获取对应的图标。
1, 获取文件扩展名,
2,根据文件扩展名来获取系统图标,
3, 将listview的显示属性View修改为:SmallIcon
4, 获取对应图标的index 并赋值给ListViewItem
首先是自定义的类:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Reflection;
using System.Collections.Generic;
namespace ALM_Resource_Sync.Lib
{
public static class Icons
{
#region Custom exceptions class
public class IconNotFoundException : Exception
{
public IconNotFoundException(string fileName, int index)
: base(string.Format("Icon with Id = {0} wasn't found in file {1}", index, fileName))
{
}
}
public class UnableToExtractIconsException : Exception
{
public UnableToExtractIconsException(string fileName, int firstIconIndex, int iconCount)
: base(string.Format("Tryed to extract {2} icons starting from the one with id {1} from the \"{0}\" file but failed", fileName, firstIconIndex, iconCount))
{
}
}
#endregion
#region DllImports
/// <summary>
/// Contains information about a file object.
/// </summary>
struct SHFILEINFO
{
/// <summary>
/// Handle to the icon that represents the file. You are responsible for
/// destroying this handle with DestroyIcon when you no longer need it.
/// </summary>
public IntPtr hIcon;
/// <summary>
/// Index of the icon image within the system image list.
/// </summary>
public IntPtr iIcon;
/// <summary>
/// Array of values that indicates the attributes of the file object.
/// For information about these values, see the IShel