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、效果圖:
【歡迎轉載】
轉載請表明出處: 樂學習