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


当前回答

注意,为了实现这一点,你还需要在_drawEnter…中设置dragDropEffect。

private void Form1_DragEnter(object sender, DragEventArgs e)
{
    Console.WriteLine("DragEnter!");
    e.Effect = DragDropEffects.Copy;
}

来源:在c# Winforms应用程序中拖放不工作

其他回答

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

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

一些示例代码:

  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);
    }
  }

注意,为了实现这一点,你还需要在_drawEnter…中设置dragDropEffect。

private void Form1_DragEnter(object sender, DragEventArgs e)
{
    Console.WriteLine("DragEnter!");
    e.Effect = DragDropEffects.Copy;
}

来源:在c# Winforms应用程序中拖放不工作

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