Subclass TreeView
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
class DirectoryTreeView: TreeView
{
public DirectoryTreeView()
{
ImageList = new ImageList();
ImageList.Images.Add(new Bitmap(GetType(), "FLOPPY.BMP"));
ImageList.Images.Add(new Bitmap(GetType(), "FOLD.BMP"));
ImageList.Images.Add(new Bitmap(GetType(), "OPENFOLD.BMP"));
RefreshTree();
}
public void RefreshTree()
{
BeginUpdate();
Nodes.Clear();
string[] astrDrives = Directory.GetLogicalDrives();
foreach (string str in astrDrives)
{
TreeNode tnDrive = new TreeNode(str, 0, 0);
Nodes.Add(tnDrive);
AddDirectories(tnDrive);
if (str == "C:\\")
SelectedNode = tnDrive;
}
EndUpdate();
}
void AddDirectories(TreeNode tn)
{
tn.Nodes.Clear();
string strPath = tn.FullPath;
DirectoryInfo dirinfo = new DirectoryInfo(strPath);
DirectoryInfo[] adirinfo;
adirinfo = dirinfo.GetDirectories();
foreach (DirectoryInfo di in adirinfo)
{
TreeNode tnDir = new TreeNode(di.Name, 1, 2);
tn.Nodes.Add(tnDir);
}
}
protected override void OnBeforeExpand(TreeViewCancelEventArgs tvcea)
{
base.OnBeforeExpand(tvcea);
BeginUpdate();
foreach (TreeNode tn in tvcea.Node.Nodes)
AddDirectories(tn);
EndUpdate();
}
}
class DirectoriesAndFiles: Form
{
DirectoryTreeView dirtree;
Panel panel;
TreeNode tnSelect;
public static void Main()
{
Application.Run(new DirectoriesAndFiles());
}
public DirectoriesAndFiles()
{
Text = "Directories and Files";
BackColor = SystemColors.Window;
ForeColor = SystemColors.WindowText;
panel = new Panel();
panel.Parent = this;
panel.Dock = DockStyle.Fill;
panel.Paint += new PaintEventHandler(PanelOnPaint);
Splitter split = new Splitter();
split.Parent = this;
split.Dock = DockStyle.Left;
split.BackColor = SystemColors.Control;
dirtree = new DirectoryTreeView();
dirtree.Parent = this;
dirtree.Dock = DockStyle.Left;
dirtree.AfterSelect += new TreeViewEventHandler(DirectoryTreeViewOnAfterSelect);
Menu = new MainMenu();
Menu.MenuItems.Add("View");
MenuItem mi = new MenuItem("Refresh", new EventHandler(MenuOnRefresh), Shortcut.F5);
Menu.MenuItems[0].MenuItems.Add(mi);
}
void DirectoryTreeViewOnAfterSelect(object obj, TreeViewEventArgs tvea)
{
tnSelect = tvea.Node;
panel.Invalidate();
}
void PanelOnPaint(object obj, PaintEventArgs pea)
{
if (tnSelect == null)
return;
Panel panel = (Panel) obj;
Graphics grfx = pea.Graphics;
DirectoryInfo dirinfo = new DirectoryInfo(tnSelect.FullPath);
FileInfo[] afileinfo;
Brush brush = new SolidBrush(panel.ForeColor);
int y = 0;
afileinfo = dirinfo.GetFiles();
foreach (FileInfo fileinfo in afileinfo)
{
grfx.DrawString(fileinfo.Name, Font, brush, 0, y);
y += Font.Height;
}
}
void MenuOnRefresh(object obj, EventArgs ea)
{
dirtree.RefreshTree();
}
}
Related examples in the same category