我曾在Borland的Turbo c++环境中看到过这一点,但我不确定如何在我正在开发的c#应用程序中实现这一点。是否有最佳实践或陷阱需要注意?


当前回答

注意windows vista/windows 7的安全权限——如果你以管理员身份运行Visual Studio,当你在Visual Studio中运行程序时,你将不能将文件从非管理员资源管理器窗口拖到程序中。拖相关事件甚至不会火!

其他回答

一些示例代码:

  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      this.AllowDrop = true;
      this.DragEnter += new DragEventHandler(Form1_DragEnter);
      this.DragDrop += new DragEventHandler(Form1_DragDrop);
    }

    void Form1_DragEnter(object sender, DragEventArgs e) {
      if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
    }

    void Form1_DragDrop(object sender, DragEventArgs e) {
      string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
      foreach (string file in files) Console.WriteLine(file);
    }
  }

在Windows窗体中,设置控件的AllowDrop属性,然后监听DragEnter事件和DragDrop事件。

当DragEnter事件触发时,将参数的allowedeeffect设置为非none的值(例如e.c effect = DragDropEffects.Move)。

当DragDrop事件触发时,您将得到一个字符串列表。每个字符串都是被删除文件的完整路径。

另一个常见的陷阱是认为你可以忽略表单DragOver(或DragEnter)事件。我通常使用表单的DragOver事件来设置allowedeeffect,然后使用特定控件的DragDrop事件来处理已删除的数据。

Judah Himango和Hans Passant的解决方案在设计器中可用(我目前使用VS2015):

你需要注意一个陷阱。在拖放操作中作为数据对象传递的任何类都必须是可序列化的。因此,如果你试图传递一个对象,它不工作,确保它可以序列化,因为这几乎肯定是问题所在。这已经抓了我几次了!