是否可以将文件直接拖到窗体上,还是必须放在窗体上的控件上?我已经使用下面的代码很长一段时间了,但这需要你拖到ListView
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
this.listView1.AllowDrop = true;
this.listView1.Columns.Add("File name");
this.listView1.Dock = DockStyle.Fill;
this.listView1.SmallImageList = this.imageList1;
this.listView1.View = View.Details;
this.listView1.DragEnter += new DragEventHandler(listView1_DragEnter);
this.listView1.DragDrop += new DragEventHandler(listView1_DragDrop);
}
void listView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("FileDrop") &&
(e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
{
e.Effect = DragDropEffects.Copy;
}
}
void listView1_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("FileDrop") &&
(e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy)
{
string[] filePaths = (string[])e.Data.GetData("FileDrop");
ListViewItem[] items = new ListViewItem[filePaths.Length];
string filePath;
for (int index = 0; index < filePaths.Length; index++)
{
filePath = filePaths[index];
if (!this.imageList1.Images.Keys.Contains(filePath))
{
this.imageList1.Images.Add(filePath,
Icon.ExtractAssociatedIcon(filePath));
}
items[index] = new ListViewItem(filePath, filePath);
}
this.listView1.Items.AddRange(items);
}
}
答案 0 :(得分:2)
this.DragDrop += new DragEventHandler(form_DragDrop);