I,
我正在创建一个带有ListView对象的VB窗体,其中包含Excel,Word或Pdf图标的图像,以及指向所显示文档的链接(待制作)
编译时,文档名称显示在listView中,但不显示在图标中。你知道我的代码中缺少什么吗?
据我所知,“ExtractAssociatedIcon”方法需要文件的完整路径,但似乎这里没有收集Icon。
由于
Imports System
Imports System.IO
Imports System.Drawing
[...]
Dim dirInfo As DirectoryInfo
Dim fileInfo As FileInfo
Dim exePath As String
Dim exeIcon As Drawing.Icon
dirInfo = New DirectoryInfo("G:\XXX\XXX\XXX\XXX\XXX")
'We use this For...Each to iterate over the collection of files in the folder
For Each fileInfo In dirInfo.GetFiles
'We can only find associated exes by extension, so don't show any files that have no extension
If fileInfo.Extension = String.Empty Then
Else
'Use the function to get the path to the executable for the file
exePath = fileInfo.FullName
'Use ExtractAssociatedIcon to get an icon from the path
exeIcon = Drawing.Icon.ExtractAssociatedIcon(exePath)
'Add the icon if we haven't got it already, with the executable path as the key
If ImageList1.Images.ContainsKey(exePath) Then
Else
ImageList1.Images.Add(exePath, exeIcon)
End If
'Add the file to the ListView, with the executable path as the key to the ImageList's image
ListView1.View = View.LargeIcon
ListView1.Items.Add(fileInfo.Name, exePath)
End If
Next
答案 0 :(得分:1)
1)您需要设置ListView
的{{3}}和/或SmallImageList属性:
ListView1.LargeImageList = ImageList1
ListView1.SmallImageList = ImageList1
2)将它放在代码的顶部。 (不在For Each
循环中)
ListView1.View = View.LargeIcon
3)此外,请确保您不添加空图标,也不要设置无效的图像键:
If (ImageList1.Images.ContainsKey(exePath)) Then
ListView1.Items.Add(fileInfo.Name, exePath)
ElseIf (Not exeIcon Is Nothing) Then
ImageList1.Images.Add(exePath, exeIcon)
ListView1.Items.Add(fileInfo.Name, exePath)
Else
ListView1.Items.Add(fileInfo.Name)
End If
示例强>
以下代码经过测试并正常运行:
ListView1.LargeImageList = ImageList1
ListView1.SmallImageList = ImageList1
ListView1.View = View.LargeIcon
Dim dirInfo As DirectoryInfo
Dim fileInfo As FileInfo
Dim exeIcon As System.Drawing.Icon
dirInfo = New DirectoryInfo("...")
For Each fileInfo In dirInfo.GetFiles
If (Not String.IsNullOrEmpty(fileInfo.Extension)) Then
exeIcon = System.Drawing.Icon.ExtractAssociatedIcon(fileInfo.FullName)
If (ImageList1.Images.ContainsKey(fileInfo.FullName)) Then
ListView1.Items.Add(fileInfo.Name, fileInfo.FullName)
ElseIf (Not exeIcon Is Nothing) Then
ImageList1.Images.Add(fileInfo.FullName, exeIcon)
ListView1.Items.Add(fileInfo.Name, fileInfo.FullName)
Else
ListView1.Items.Add(fileInfo.Name)
End If
End If
Next