通过托放文件到TextBox,在其中显示文件名称的方法

来源:互联网 发布:游骑兵和海豹知乎 编辑:程序博客网 时间:2024/04/29 18:39

 通过写托放事件实现,示例代码如下:

  1.     public partial class Form2 : Form
  2.     {
  3.         public Form2()
  4.         {
  5.             InitializeComponent();
  6.             this.textBox1.Multiline = true;
  7.             //文本框允许拖放操作
  8.             this.textBox1.AllowDrop = true;
  9.             //在完成拖放操作时发生
  10.             this.textBox1.DragDrop+=new DragEventHandler(textBox1_DragDrop);
  11.             //在将文件拖入文本框的边界时发生
  12.             this.textBox1.DragEnter+=new DragEventHandler(textBox1_DragEnter);
  13.         }
  14.         protected void textBox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
  15.         {
  16.             IDataObject dataObject = e.Data;
  17.             //是文件拖放
  18.             if (dataObject.GetDataPresent(DataFormats.FileDrop))
  19.             {
  20.                 e.Effect = DragDropEffects.Copy;
  21.             }
  22.         }
  23.         protected void textBox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
  24.         {
  25.             
  26.             IDataObject dataObject = e.Data;
  27.             if (dataObject == nullreturn;
  28.             if (dataObject.GetDataPresent(DataFormats.FileDrop))
  29.             {
  30.                 ////拖放的文件,可以多个
  31.                 string[] files = (string[])dataObject.GetData(DataFormats.FileDrop);
  32.                 foreach (string file in files)
  33.                 {
  34.                     System.IO.FileInfo fi = new System.IO.FileInfo(file);
  35.                     //接收的文件类型
  36.                     if (fi.Extension == ".doc" || fi.Extension == ".xsl" || fi.Extension == ".rar")
  37.                     {
  38.                         this.textBox1.Text += "文件名:" + fi.Name + "/t路径:" + fi.Directory + "/r/n";
  39.                     }
  40.                 }
  41.             }
  42.         }
  43.     }