2014-01-22 22 views
0

我,在ListView控件對象顯示應用程序圖標(和名稱)

我創建包含的Excel,Word或PDF圖標,圖像與一個鏈接顯示的文檔一個ListView對象VB表格(可製作)

編譯時,文檔的名稱顯示在listView中,而不是圖標。你知道我的代碼中缺少什麼嗎?

據我所知,「ExtractAssociatedIcon」方法需要文件的完整路徑,但似乎沒有在這裏收集圖標。

感謝

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 

回答

1

1)您需要設置SmallImageList和/或ListViewLargeImageList屬性:

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 
相關問題