如何:提取与 Windows 窗体中的文件关联的图标
更新:2007 年 11 月
很多文件都有嵌入式图标,为关联的文件类型提供可视化表示形式。例如,Microsoft Word 文档包含一个将其标识为 Word 文档的图标。在列表控件或表控件中显示文件时,您可能希望将表示文件类型的图标显示在每个文件名旁边。可以使用 ExtractAssociatedIcon 方法轻松实现此目的。
示例
下面的代码示例演示如何提取与文件关联的图标并在 ListView 控件中显示文件名及其关联图标。
Private listView1 As ListView
Private imageList1 As ImageList
Public Sub ExtractAssociatedIconEx()
' Initialize the ListView, ImageList and Form.
listView1 = New ListView()
imageList1 = New ImageList()
listView1.Location = New Point(37, 12)
listView1.Size = New Size(161, 242)
listView1.SmallImageList = imageList1
listView1.View = View.SmallIcon
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.listView1)
Me.Text = "Form1"
' Get the c:\ directory.
Dim dir As New System.IO.DirectoryInfo("c:\")
Dim item As ListViewItem
listView1.BeginUpdate()
Dim file As FileInfo
For Each file In dir.GetFiles()
' Set a default icon for the file.
Dim iconForFile As Icon = SystemIcons.WinLogo
item = New ListViewItem(file.Name, 1)
' Check to see if the image collection contains an image
' for this extension, using the extension as a key.
If Not (imageList1.Images.ContainsKey(file.Extension)) Then
' If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName)
imageList1.Images.Add(file.Extension, iconForFile)
End If
item.ImageKey = file.Extension
listView1.Items.Add(item)
Next file
listView1.EndUpdate()
End Sub
ListView listView1;
ImageList imageList1;
public void ExtractAssociatedIconEx()
{
// Initialize the ListView, ImageList and Form.
listView1 = new ListView();
imageList1 = new ImageList();
listView1.Location = new Point(37, 12);
listView1.Size = new Size(151, 262);
listView1.SmallImageList = imageList1;
listView1.View = View.SmallIcon;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.listView1);
this.Text = "Form1";
// Get the c:\ directory.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(@"c:\");
ListViewItem item;
listView1.BeginUpdate();
// For each file in the c:\ directory, create a ListViewItem
// and set the icon to the icon extracted from the file.
foreach (FileInfo file in dir.GetFiles())
{
// Set a default icon for the file.
Icon iconForFile = SystemIcons.WinLogo;
item = new ListViewItem(file.Name, 1);
iconForFile = Icon.ExtractAssociatedIcon(file.FullName);
// Check to see if the image collection contains an image
// for this extension, using the extension as a key.
if (!imageList1.Images.ContainsKey(file.Extension))
{
// If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName);
imageList1.Images.Add(file.Extension, iconForFile);
}
item.ImageKey = file.Extension;
listView1.Items.Add(item);
}
listView1.EndUpdate();
}
编译代码
编译此示例:
将前面的代码粘贴到一个 Windows 窗体中,并从该窗体的构造函数或 Load 事件处理方法中调用 ExtractAssociatedIconExample 方法。
您需要确保窗体导入 System.IO 命名空间。