0

So basically what I want is the user presses a browse button and a FolderBroswerDialog pops up. The user then selects a folder and the ViewList is then populated with all the images in that folder in Icon view. How can I do this? The code I currently have will select all the files from a folder and display them in the ListView, however there are no icons. How can I get icons?
Here is the code I currently have...

private void button1_Click(object sender, EventArgs e)
{

    FolderBrowserDialog browsefolder = new FolderBrowserDialog();
    if (browsefolder.ShowDialog() == DialogResult.OK)
    {
        listView1.Items.Clear();

        string[] myfiles = Directory.GetFiles(folderPicker.SelectedPath);
        foreach (string file in myfiles)
        {
            string fileName = Path.GetFileNameWithoutExtension(file);
            ListViewItem myitem = new ListViewItem(fileName);
            myitem.Tag = file;
            listView1.Items.Add(myitem);
        }

    }
}
Ben
  • 335
  • 3
  • 12

1 Answers1

1

This is not so easy to do in an accurate and performant way. The quick and dirty way is to use Icon.ExtractAssociatedIcon() and add the returned icon to the ImageList associated with the list view. But you won't get the exact same icons you'd see in Explorer. That requires pinvoking SHGetFileInfo(), painful to do yourself but the code is easy to google.

An entirely different approach is to embed the Explorer window into your own form instead of using a ListView. With the major advantages that you'll get the exact same look and you'll automatically get the background thread that looks up icons while your program keeps responsive. With the disadvantage that this won't work for XP. The classes you need are part of the Windows API Code Pack.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536