Практическое руководство. Извлечение связанного с файлом значка в Windows Forms
Многие файлы имеют внедренные значки, обеспечивающие визуальное представление связанного типа файла. Например, документы Microsoft Word имеют значок, который идентифицирует их как документы Word. При отображении файлов в элементе управления "Список" или "Таблица" может потребоваться отобразить значок, представляющий тип файла, рядом с каждым именем файла. Это можно легко сделать с помощью метода ExtractAssociatedIcon.
Пример
В приведенном ниже примере кода показано, как извлечь связанный с файлом значок и отобразить имя файла и связанный с ним значок в элементе управления ListView.
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 (System.IO.FileInfo file in dir.GetFiles())
{
// Set a default icon for the file.
Icon iconForFile = 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 (!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();
}
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 System.IO.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
Компиляция кода
Чтобы скомпилировать пример, выполните указанные ниже действия.
Вставьте приведенный выше код в форму Windows Forms и вызовите метод
ExtractAssociatedIconExample
из конструктора формы или метода обработки событий Load.Необходимо убедиться в том, что в форму импортировано пространство имен System.IO.
См. также
.NET Desktop feedback
Обратная связь
https://aka.ms/ContentUserFeedback.
Ожидается в ближайшее время: в течение 2024 года мы постепенно откажемся от GitHub Issues как механизма обратной связи для контента и заменим его новой системой обратной связи. Дополнительные сведения см. в разделеОтправить и просмотреть отзыв по