c# - 从 TreeView 中的图标设置图像

标签 c# winforms treeview

我正在编写我自己的基于 C# 的应用程序启动器,虽然我让它填充 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 中?

最佳答案

首先,将图像添加为资源并定义图像列表:

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

关于c# - 从 TreeView 中的图标设置图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13782649/

相关文章:

c# - 仅当焦点在文本框上时显示按钮

winforms - 当子列表更改时,我应该如何处理 INotifyPropertyChanged

c# - 如何在 ASP.NET 中生成 TreeView ?

c# - 在 PayPal 沙箱中测试定期付款

c# - 如何访问 ConcurrentDictionary 以及如何将其序列化?

c# - SetField 无法将 DBNull.Value 转换为 System.Int32

java - 无法连接到 .NET 中的远程 MySQL (MariaDB) 数据库,但可以使用 Java

javascript - 寻找家谱

delphi - Treeview Imageindex-图像不断变化

c# - 在类上使用 DisplayAttribute