【问题标题】:RichTextBox only inserts first file on Drag&DropRichTextBox 仅在拖放时插入第一个文件
【发布时间】:2016-04-14 12:02:32
【问题描述】:

使用 Drag&Drop 将文件拖放到 RichTextBox 时,即使拖动了更多文件,也只会插入 1 个文件。如何改变行为?


示例表格,说明问题:

using System.Collections.Specialized;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        RichTextBox rtb;

        public Form1()
        {
            rtb = new System.Windows.Forms.RichTextBox();
            rtb.Dock = DockStyle.Fill;
            rtb.AllowDrop = true;
            Controls.Add(rtb);

            rtb.DragEnter += Rtb_DragEnter;
            rtb.DragDrop += Rtb_DragDrop;
        }

        private void Rtb_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }

        private void Rtb_DragDrop(object sender, DragEventArgs e)
        {
            StringCollection sFiles = new StringCollection();
            if (e.Data.GetDataPresent("FileDrop"))
            {
                sFiles.AddRange((string[])e.Data.GetData("FileDrop"));  //returns a list of files
                Clipboard.Clear();
                Clipboard.SetFileDropList(sFiles);
                rtb.Paste(DataFormats.GetFormat(DataFormats.FileDrop));
            }
        }
    }
}

【问题讨论】:

    标签: c# winforms drag-and-drop richtextbox


    【解决方案1】:

    这似乎是默认的复制行为。使用[Ctrl]+[v]也会出现同样的问题。

    您可以通过一个接一个地粘贴文件来解决这个问题:

    private void Rtb_DragDrop(object sender, DragEventArgs e)
    {
        StringCollection sFiles = new StringCollection();
        if (e.Data.GetDataPresent("FileDrop"))
        {
            foreach (string file in (string[])e.Data.GetData("FileDrop"))
            {
                Clipboard.Clear();
                sFiles.Clear();
                sFiles.Add(file);
                Clipboard.SetFileDropList(sFiles);
                rtb.Paste();  //it's not necessary to specify the format
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 2017-04-09
      相关资源
      最近更新 更多