C#winform拖拽实现获得文件路径


1、关键知识点说明:

通过DragEnter事件获得被拖入窗口的“信息”(可以是若干文件,一些文字等等),在DragDrop事件中对“信息”进行解析。窗体的AllowDrop属性必须设置成true;且必须有DragEnter事件(单独写DragDrop事件是不会具有拖拽功能的)。


2、经验积累:


 

3、代码实现:

 1 using System;
 2 using System.Windows.Forms;
 3 
 4 namespace showpath
 5 {
 6     public partial class Form1 : Form
 7     {
 8         public Form1()
 9         {
10             InitializeComponent();
11         }
12 
13         private void textBox1_TextChanged(object sender, EventArgs e)
14         {
15 
16         }
17 
18         private void Form1_Load(object sender, EventArgs e)
19         {
20 
21         }
22 
23         private void Form1_DragEnter(object sender, DragEventArgs e)                                         //获得“信息”
24         {
25             if (e.Data.GetDataPresent(DataFormats.FileDrop))
26                 e.Effect = DragDropEffects.All;                                                              //重要代码:表明是所有类型的数据,比如文件路径
27             else
28                 e.Effect = DragDropEffects.None;
29         }
30 
31         private void Form1_DragDrop(object sender, DragEventArgs e)                                          //解析信息
32         {
33             string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();       //获得路径
34             textBox1.Text = path;                                                                            //由一个textBox显示路径
35         }
36     }
37 }

4、效果图:


【欢迎转载】

 转载请表明出处: 乐学习

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM