通过写托放事件实现,示例代码如下:
- public partial class Form2 : Form
- {
- public Form2()
- {
- InitializeComponent();
- this.textBox1.Multiline = true;
- //文本框允许拖放操作
- this.textBox1.AllowDrop = true;
- //在完成拖放操作时发生
- this.textBox1.DragDrop+=new DragEventHandler(textBox1_DragDrop);
- //在将文件拖入文本框的边界时发生
- this.textBox1.DragEnter+=new DragEventHandler(textBox1_DragEnter);
- }
- protected void textBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
- {
- IDataObject dataObject = e.Data;
- //是文件拖放
- if (dataObject.GetDataPresent(DataFormats.FileDrop))
- {
- e.Effect = DragDropEffects.Copy;
- }
- }
- protected void textBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
- {
- IDataObject dataObject = e.Data;
- if (dataObject == null) return;
- if (dataObject.GetDataPresent(DataFormats.FileDrop))
- {
- 拖放的文件,可以多个
- string[] files = (string[])dataObject.GetData(DataFormats.FileDrop);
- foreach (string file in files)
- {
- System.IO.FileInfo fi = new System.IO.FileInfo(file);
- //接收的文件类型
- if (fi.Extension == ".doc" || fi.Extension == ".xsl" || fi.Extension == ".rar")
- {
- this.textBox1.Text += "文件名:" + fi.Name + "/t路径:" + fi.Directory + "/r/n";
- }
- }
- }
- }
- }