WINFORM学习手册——创建资源管理器
一、新建解决方案:
二、将toolstrip拖入窗体
三、将splitcontainer拖入窗体
四、将treeview拖入panel1,并设置其dock属性为fill
五、将ListView拖入panel2,并设置其dock属性为fill
六、在ToolStrip上添加一个Label和一个Combobox
七、为ComboBox绑定数据源:
八、将ImageList拖入主窗体,并修改其属性:
九、修改ListView的LargeImageList和SmallImageList属性:
十、主窗体的Load事件加入如下代码:
/// <summary> /// 加载数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Explorer_Load(object sender, EventArgs e) { //设置ListView显示模式为默认时的列 this.listView1.Columns.Add("名称", 300); this.listView1.Columns.Add("修改时间",200); this.listView1.Columns.Add("大小",100); this.toolStripComboBox1.SelectedIndex = 0;//设置工具条上的ComboBox的默认选择 TreeNode root = new TreeNode("我的文档"); root.Tag = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//我的文档路径 AddNodes(root);//递归获取节点 this.treeView1.Nodes.Add(root);//将节点加载到树上 root.Expand();//展开根节点 } /// <summary> /// 获取子节点 /// </summary> /// <param name="node"></param> private void AddNodes(TreeNode node) { var dir = new System.IO.DirectoryInfo(node.Tag.ToString()); foreach (var childDir in dir.GetDirectories()) { //判断是否有权限访问 if (childDir.Attributes.HasFlag(FileAttributes.Hidden)) { continue; } TreeNode childNode = new TreeNode(childDir.Name); childNode.Tag = childDir.FullName; AddNodes(childNode); node.Nodes.Add(childNode); } }
十一、Combox的SelectedIndexChanged事件加入如下代码:
/// <summary> /// 更改ListView显示方式 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e) { var text = this.toolStripComboBox1.Text; switch (text) { case "大图标": this.listView1.View = View.LargeIcon; break; case "小图标": this.listView1.View = View.SmallIcon; break; case "默认": this.listView1.View = View.Details; break; } }
十二、TreeView的AfterSelect事件加入如下代码:
/// <summary> /// 选中后的事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { var dir = new DirectoryInfo(e.Node.Tag.ToString()); this.listView1.Items.Clear();//清除listview的数据 foreach (var file in dir.GetFiles())//遍历目录 { ListViewItem item = new ListViewItem(file.Name); var lastWrite = file.LastWriteTime; //添加更新时间 item.SubItems.Add(lastWrite.ToShortDateString() + " " + lastWrite.ToShortTimeString()); //添加文件大小 item.SubItems.Add(Math.Ceiling(file.Length / 1024.0) + " KB"); //查看是否已经保存过该类型图片,如果没有,保存 if (!(this.bigImgList.Images.ContainsKey(file.Extension))) { var thisIcon = Icon.ExtractAssociatedIcon(file.FullName); this.smallImgList.Images.Add(file.Extension, thisIcon); this.bigImgList.Images.Add(file.Extension, thisIcon); } item.ImageKey = file.Extension; this.listView1.Items.Add(item); } }
执行: