C#实现简单的拖动功能

这个例子是将系统文件或目录拖动到窗体中,窗体以MessageBox的形式弹出用户拖入的文件或目录名称。

首先需要将要支持拖动的Form的AllowDrop=true;然后通过DragEnter和DragDrop事件即可,具体代码如下:

复制代码
 1  private void Form1_DragDrop(object sender, DragEventArgs e)
 2         {
 3             System.Array datas = (System.Array)e.Data.GetData(DataFormats.FileDrop);
 4             string filePathOrDirectory = (datas).GetValue(0).ToString();
 5             if (Directory.Exists(filePathOrDirectory))
 6             {
 7                 MessageBox.Show("目录:" + filePathOrDirectory);
 8             }
 9             else
10             {
11                 MessageBox.Show("文件:" + filePathOrDirectory);
12             }
13         }
14 
15         private void Form1_DragEnter(object sender, DragEventArgs e)
16         {
17             if (e.Data.GetDataPresent(DataFormats.FileDrop) == true)
18                 e.Effect = DragDropEffects.Link;
19             else
20                 e.Effect = DragDropEffects.None;
21         }
原文地址:https://www.cnblogs.com/iwangjun/p/2575438.html