Serialcoder en Français Serialcoder in English
TEL : +33 (0)9 72 13 15 17

Windows Forms FAQ resources

22. Windows Forms RichTextBox

22.3 How do I make the RichTextBox support drag and drop?


1) Set the AllowDrop property to true
2) Add handlers for both the DragEnter and DragDrop event

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

     ....

     private void richTextBox1_DragEnter(object sender,
               System.Windows.Forms.DragEventArgs e)
     {
          if (((DragEventArgs)e).Data.GetDataPresent(DataFormats.Text))
               ((DragEventArgs)e).Effect = DragDropEffects.Copy;
          else
               ((DragEventArgs)e).Effect = DragDropEffects.None;
     }

     private void richTextBox1_DragDrop(object sender, DragEventArgs e)
     {
          // Loads the file into the control.
          richTextBox1.LoadFile((String)e.Data.GetData("Text"), System.Windows.Forms.RichTextBoxStreamType.RichText);
     }

Here are VB snippets.

      AddHandler Me.richTextBox1.DragEnter, New System.Windows.Forms.DragEventHandler(AddressOf Me.richTextBox1_DragEnter)
      AddHandler Me.richTextBox1.DragDrop, New System.Windows.Forms.DragEventHandler(AddressOf Me.richTextBox1_DragEnter)

     .....


     Private Sub richTextBox1_DragEnter(sender As Object, e As System.Windows.Forms.DragEventArgs)

          If CType(e, DragEventArgs).Data.GetDataPresent(DataFormats.Text) Then
               CType(e, DragEventArgs).Effect = DragDropEffects.Copy
          Else
               CType(e, DragEventArgs).Effect = DragDropEffects.None
          End If

     End Sub 'richTextBox1_DragEnter


     Private Sub richTextBox1_DragDrop(sender As Object, e As DragEventArgs)

          ' Loads the file into the control.
          richTextBox1.LoadFile(CType(e.Data.GetData("Text"), [String]), System.Windows.Forms.RichTextBoxStreamType.RichText)

     End Sub 'richTextBox1_DragDrop