2012-12-08 69 views
5

我正在編寫自己的基於C#的應用程序啓動器,並且,雖然我得到它來填充TreeView並啓動應用程序快捷方式,但我似乎無法弄清楚如何添加圖標作爲圖像到TreeView。我目前用於獲取文件中的代碼是:從TreeView中的圖標設置圖像

private void homeMenu_Load(object sender, EventArgs e) 
    { 
     this.ShowInTaskbar = false; 
     if (Directory.Exists((Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName + "\\Roaming\\Launcher"))) 
     { 

     } 
     else 
     { 
      Directory.CreateDirectory(Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName + "\\Roaming\\Launcher"); 
     } 

     DirectoryInfo launcherFiles = new DirectoryInfo(Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)).FullName + "\\Roaming\\Launcher"); 

     lstPrograms.Nodes.Add(CreatingDirectoryTreeNode(launcherFiles)); 

     lstPrograms.Sort(); 

    } 

    private static TreeNode CreatingDirectoryTreeNode(DirectoryInfo directoryInfo) 
    { 
     var directoryNode = new TreeNode(directoryInfo.Name); 

     foreach (var directory in directoryInfo.GetDirectories()) 
     { 
      directoryNode.Nodes.Add(CreatingDirectoryTreeNode(directory)); 
     } 

     foreach (var file in directoryInfo.GetFiles()) 
     { 
      directoryNode.Nodes.Add(new TreeNode(file.Name)); 
     } 

     return directoryNode; 
    } 

我的主要問題是增加的圖標的TreeList的ImageList中的特定節點。我知道我需要添加:

lstPrograms.ImageList.Images.Add(Icon.ExtractAssociatedIcon()); 

實際的圖標添加到圖像列表,我如何獲得該特定圖像的指數,然後將它與它的相對文件添加到TreeView

回答

10

首先,添加圖像資源和定義圖像列表:

static ImageList _imageList; 
public static ImageList ImageList 
{ 
    get 
    { 
     if (_imageList == null) 
     { 
      _imageList = new ImageList(); 
      _imageList.Images.Add("Applications", Properties.Resources.Image_Applications); 
      _imageList.Images.Add("Application", Properties.Resources.Image_Application); 
     } 
     return _imageList; 
    } 
} 

然後,設置TreeViewImageList屬性:

treeView1.ImageList = Form1.ImageList; 

然後,當你創建的節點,一個特定節點,用途:

applicationNode.ImageKey = "Application"; 
applicationNode.SelectedImageKey = "Application";