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、效果图:
【欢迎转载】
转载请表明出处: 乐学习
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步