How do I support drag-and-drop for a RichTextBox?

Platform: WPF| Category: RichTextBox

You must set the ‘AllowDrop’ property on the RichTextBox control to true and also handle both the ‘DragEnter’ and ‘DragDrop’ events.

Add event handlers to the control as given below.

[C#]

using System.Windows.Forms;
richTextBox1.DragEnter += new DragEventHandler( richTextBox1_DragEnter );
richTextBox1.DragDrop += new DragEventHandler( richTextBox1_DragDrop );

Write event handlers :
{
        private void richTextBox1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = e.Data.GetDataPresent(DataFormats.Text)
              ? DragDropEffects.Copy
              : DragDropEffects.None;
        }

        private void richTextBox1_DragDrop(object sender, DragEventArgs e)
        {
            // Load the file into the control
            string text = (string)e.Data.GetData('Text');
            richTextBox1.LoadFile(text, RichTextBoxStreamType.RichText);
        }

        public Window1()
        {
            InitializeComponent();
        }
    }

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.