最近可能有一个和DragDrop有关的项目,目前还没确定用C++还是C#做,我也在进行一些学习调查。所以就边学边写,来谈一谈在C#中的拖拽操作。这篇文章主要是介绍.NET中拖拽的实现。
一 C#中Drap and Drop的用法
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listView1.View = View.List;
listView2.View = View.List;
}
private void listView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void listView1_DragLeave(object sender, EventArgs e)
{
}
private void listView1_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void listView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
String[] files = (String[])e.Data.GetData(DataFormats.FileDrop);
foreach (String s in files)
{
ListViewItem item = new ListViewItem(s);
listView1.Items.Add(item);
}
}
}
private void listView1_ItemDrag(object sender, ItemDragEventArgs e)
{
ListViewItem[] itemTo = new ListViewItem[((ListView)sender).SelectedItems.Count];
for (int i = 0; i < itemTo.Length; i++)
{
itemTo[i] = ((ListView)sender).SelectedItems[i];
}
//System.Runtime.InteropServices.ComTypes.IDataObject obj;
//System.Runtime.InteropServices.ComTypes.FORMATETC formatEtc;
//System.Runtime.InteropServices.ComTypes.STGMEDIUM stgMedium;
//formatEtc = new System.Runtime.InteropServices.ComTypes.FORMATETC()
//{
// cfFormat = 15,
// dwAspect = System.Runtime.InteropServices.ComTypes.DVASPECT.DVASPECT_CONTENT,
// lindex = 1,
// ptd = IntPtr.Zero,
// tymed = System.Runtime.InteropServices.ComTypes.TYMED.TYMED_HGLOBAL
//};
//stgMedium = new System.Runtime.InteropServices.ComTypes.STGMEDIUM()
//{
// pUnkForRelease = null,
// tymed = System.Runtime.InteropServices.ComTypes.TYMED.TYMED_HGLOBAL,
// unionmember = IntPtr.Zero
//};
//obj.SetData(formatEtc, stgMedium, true);
((ListView)(sender)).DoDragDrop(itemTo, DragDropEffects.Copy);
}
private void listView2_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(ListViewItem[])))
e.Effect = DragDropEffects.Copy;
}
private void listView2_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(ListViewItem[])))
{
ListViewItem[] files = (ListViewItem[])e.Data.GetData(typeof(ListViewItem[]));
foreach (ListViewItem s in files)
{
ListViewItem item = s.Clone() as ListViewItem;
listView2.Items.Add(item);
}
}
}
}
上面是一段使用两个ListView显示信息的代码,其中ListView1接受我们拖动一个文件到他的窗体上,并显示文件路径;而ListView2是接受我们从ListView1中拖动文件路径,显示在自己的view中。程序的运行结果入下。

继续阅读