在WinForm實現一個類似資源浏覽器的功能,需要實現將WinForm中列出的文件拖出到其他應用程序中或者從其他應用程序中將文件拖入到Winform應用中。網上有一些文章介紹這種功能,但都比較零散,缺少一個完整的例子。為此我編寫了一個較完整的實現文件拖入和拖出的例子,並撰寫此文一步步講解如果實現類似功能。
步驟1 放置一個 ListVIEw 到 Winform窗體中 並初始化如下屬性:
listView.View = VIEw.Details;
listVIEw.AllowDrop = true;
步驟2 撰寫一個目錄文件列表顯示的函數
/**//// <summary>
/// List files in the folder
/// </summary>
/// <param name="directory">the directory of the folder</param>
private void ListFolder(string directory)
{
labelCurFolder.Text = directory;
String[] fileList = System.IO.Directory.GetFiles(directory);
listVIEwFolder.Items.Clear();
listVIEwFolder.Columns.Clear();
listVIEwFolder.Columns.Add("Name", 300);
listVIEwFolder.Columns.Add("Size", 100);
listVIEwFolder.Columns.Add("Time", 200);
foreach (string fileName in fileList)
{
//Show file name
ListViewItem itemName = new ListVIEwItem(System.IO.Path.GetFileName(fileName));
itemName.Tag = fileName;
//Show file icon
IconImageProvider iconImageProvider = new IconImageProvider(listVIEwFolder.SmallImageList,
listVIEwFolder.LargeImageList);
itemName.ImageIndex = iconImageProvider.GetIconImageIndex(fileName);
//Show file size
System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);
long size = fileInfo.Length;
String strSize;
if (size < 1024)
{
strSize = size.ToString();
}
else if (size < 1024 * 1024)
{
strSize = String.Format("{0:###.##}KB", (float)size / 1024);
}
else if (size < 1024 * 1024 * 1024)
{
strSize = String.Format("{0:###.##}MB", (float)size / (1024 * 1024));
}
else
{
strSize = String.Format("{0:###.##}GB", (float)size / (1024 * 1024 * 1024));
}
ListViewItem.ListViewSubItem subItem = new ListViewItem.ListVIEwSubItem();
subItem.Text = strSize;
subItem.Tag = size;
itemName.SubItems.Add(subItem);
//Show file time
subItem = new ListViewItem.ListVIEwSubItem();
DateTime fileTime = System.IO.File.GetLastWriteTime(fileName);
subItem.Text = (string)fileTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"); ;
subItem.Tag = fileTime;
itemName.SubItems.Add(subItem);
listVIEwFolder.Items.Add(itemName);
}
}
上面代碼中有一段顯示圖標的代碼由於和拖動無關,我就不貼出來了,感興趣可以下載完整的代碼去看。