Setting images from icons in a TreeView

c#, treeview, winforms

Solution

First, add the images as resources and define your image list:

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;
    }
}

Then, set the `ImageList` property of the `TreeView`:

treeView1.ImageList = Form1.ImageList;

Then, when you create the nodes, for a specific node, use:

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

Problem

I'm writing my own C#-based application launcher, and, while I get it to populate the `TreeView` and launch application shortcuts in it, I can't seem to figure out how to add the icons as images to the `TreeView`. My current code for getting the files is: ``` 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; } ``` The main problem I have is adding the icon to the TreeList's ImageList to the particular node. I know I need to add: ``` lstPrograms.ImageList.Images.Add(Icon.ExtractAssociatedIcon()); ``` to actually add the icon to the image list, how do I get that particular image's index, then add it to the `TreeView` with its relative file?

Original source