Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > .NET Frameworks (точка нет фреймворки) > Windows Forms
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 04.05.2016, 23:51   #1
Restrat
Новичок
Джуниор
 
Регистрация: 08.01.2016
Сообщений: 2
По умолчанию Listview загрузка системних иконок

Добрый вечер, помогите решить проблему я написал вот такой код. Код для загрузки иконок нашел в интернете и переделал его под свой проводник.
Код:
public partial class Form1 : Form
    {
        IntPtr hImgLarge;
        System.Drawing.Icon largeIcon;
        SHFILEINFO shinfo = new SHFILEINFO();
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 256)]
            public string szDisplayName;
            [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };
        [System.Runtime.InteropServices.DllImport("Shell32.dll")]
        private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, int cbFileInfo, uint uFlags);
 
        public Form1()
        {
            InitializeComponent();
            GetDriveNodes();
        }
        private void GetDriveNodes()
        {
            try
            {
                foreach (string path in Environment.GetLogicalDrives())
                    if (new DirectoryInfo(path).Exists)
                    {
                        TreeNode driveNode = new TreeNode { Text = path };
                        FillTreeNode(driveNode, path);
                        treeView1.Nodes.Add(driveNode);
                    }
            }
            catch (Exception) { }
        }
 
        void treeView1_GetFolders(object sender, TreeViewCancelEventArgs e)
        {
            try
            {
                foreach (var dir in Directory.GetDirectories(e.Node.FullPath))
                {
                    TreeNode dirNode = new TreeNode(new DirectoryInfo(dir).Name);
                    FillTreeNode(dirNode, dir);
                    e.Node.Nodes.Add(dirNode);
                }
            }
            catch (Exception) { }
        }
 
        void treeView1_GetFiles(object sender, TreeViewCancelEventArgs e)
        {
            try
            {
                foreach (var dir in Directory.GetFiles(e.Node.FullPath))
                {
                    TreeNode dirNode = new TreeNode(new DirectoryInfo(dir).Name);
                    FillTreeNode(dirNode, dir);
                    e.Node.Nodes.Add(dirNode);
                }
            }
            catch (Exception) { }
        }
 
        void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            e.Node.Nodes.Clear();
            treeView1_GetFolders(sender, e);
            treeView1_GetFiles(sender, e);
            GetItems(e.Node.FullPath);
        }
 
        private void FillTreeNode(TreeNode driveNode, string path)
        {
            try
            {
                foreach (string dir in Directory.GetFileSystemEntries(path))
                {
                    TreeNode dirNode = new TreeNode();
                    driveNode.Nodes.Add(dirNode);
                }
            }
            catch (Exception) { }
        }

        private void listView1_GetFolders(string[] folders, ImageList largeImageList)
        {
            try
            {
                foreach (string f in folders)
                {
                    hImgLarge = SHGetFileInfo(f, 0, ref shinfo, System.Runtime.InteropServices.Marshal.SizeOf(shinfo), 0x100 | 0x0);
                    largeIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
 
                    string[] ss = f.Split(new char[] { '\\' });
                    largeImageList.Images.Add(ss[ss.Length - 1], largeIcon);
                    listView1.Items.Add(ss[ss.Length - 1], ss[ss.Length - 1]);
                }
            }
            catch (Exception) { }
        }
 
        private void listView1_GetFiles(string[] files, ImageList largeImageList)
        {
            try
            {
                foreach (string f in files)
                {
                    hImgLarge = SHGetFileInfo(f, 0, ref shinfo, System.Runtime.InteropServices.Marshal.SizeOf(shinfo), 0x100 | 0x0);
                    largeIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
 
                    string[] ss = f.Split(new char[] { '\\' });
                    largeImageList.Images.Add(ss[ss.Length - 1], largeIcon);
                    listView1.Items.Add(ss[ss.Length - 1], ss[ss.Length - 1]);
                }
            }
            catch (Exception) { }
        }
 
        private void GetItems(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    ImageList largeImageList = new ImageList();
                    largeImageList.ColorDepth = ColorDepth.Depth32Bit;
                    largeImageList.ImageSize = new System.Drawing.Size(32, 32);
 
                    listView1.LargeImageList = largeImageList;
                    listView1.Items.Clear();
 
                    listView1_GetFolders(Directory.GetDirectories(path), largeImageList);
                    listView1_GetFiles(Directory.GetFiles(path), largeImageList);
                }
            }
            catch (Exception) { }
        }
    }
У меня возникла проблема, когда с самого начала я выбираю какой-то диск, подгружает все нормально, но потом, я так понял, берет самую последнею иконку и подставляет под все папки и файлы, не знаю как исправить. Заранее спасибо.
Restrat вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Загрузка в ListView nefakt Общие вопросы Delphi 9 25.11.2012 15:17
Загрузка иконок в Listview tsar_ Общие вопросы Delphi 0 19.12.2011 15:20
Вывод иконок программ в ListView в стиле vsReport Человек_Борща Общие вопросы Delphi 1 09.11.2010 13:27
ListView вывод иконок Rolls Компоненты Delphi 2 13.05.2010 07:56
Загрузка иконок файлов igroman Общие вопросы Delphi 4 29.05.2008 09:00