【问题标题】:drag files or folders in textbox? C#在文本框中拖动文件或文件夹? C#
【发布时间】:2010-11-25 03:02:32
【问题描述】:

如何将文件或文件夹拖到文本框中?我想把文件夹名放在那个文本框中。 C# .NET

【问题讨论】:

    标签: c# .net drag-and-drop


    【解决方案1】:

    我根据link编写了这段代码

      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
          textBox1.AllowDrop = true;
          textBox1.DragEnter += new DragEventHandler(textBox1_DragEnter);
          textBox1.DragDrop += new DragEventHandler(textBox1_DragDrop);
    
        }
    
        private void textBox1_DragEnter(object sender, DragEventArgs e)
        {
          if (e.Data.GetDataPresent(DataFormats.FileDrop))
            e.Effects = DragDropEffects.Copy;
          else
            e.Effects = DragDropEffects.None; 
        }
    
        private void textBox1_DragDrop(object sender, DragEventArgs e)
        {
          string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);
    
    
        string s="";
    
        foreach (string File in FileList)
        s = s+ " "+ File ;
        textBox1.Text = s;
        }
      }
    

    【讨论】:

      【解决方案2】:

      在您的 TextBox 上将 AllowDrop 设置为 true,并为 DragDrop 和 DragEnter 事件编写以下代码:

          private void textBox1_DragEnter(object sender, DragEventArgs e)
          {
              if (e.Data.GetDataPresent(DataFormats.FileDrop))
              {
                  e.Effect = DragDropEffects.Copy;
              }
          }
      
          private void textBox1_DragDrop(object sender, DragEventArgs e)
          {
              if (e.Data.GetDataPresent(DataFormats.FileDrop))
              {
                  string[] fileNames = (string[])e.Data.GetData(DataFormats.FileDrop);
                  textBox1.Lines = fileNames;
              }
          }
      

      【讨论】:

        【解决方案3】:

        CodeProject has a really nice example 这样做,包括如何启用双向拖放(从资源管理器到您的应用程序,以及从您的应用程序到资源管理器)。

        【讨论】:

          【解决方案4】:

          Control 有各种用于处理拖放的事件 - 您可能只需要查看 DragDrop 事件即可。

          【讨论】:

            【解决方案5】:

            如果您收到以下错误消息,这适用于我在使用 Visual Studio 2015 时,请尝试 e.Effect 代替 e.Effects

            严重性代码描述项目文件行抑制状态 错误 CS1061“DragEventArgs”不包含“Effects”的定义,并且找不到接受“DragEventArgs”类型的第一个参数的扩展方法“Effects”(您是否缺少 using 指令或程序集引用?)

            【讨论】:

              猜你喜欢
              • 2020-02-10
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-08-08
              • 2012-10-21
              • 2014-09-20
              • 1970-01-01
              • 2010-11-26
              相关资源
              最近更新 更多