Question Drag Selected Text FROM Text Box and Drop in Other Applications

starryeye

New member
Joined
Aug 4, 2008
Messages
1
Programming Experience
Beginner
Hi I am having trouble finding information on how to code a drag and drop operation.

I have vb.net 2008

What I am trying to do is:
Drag selected/highlighted text from a simple text box in my program to any other application.

(I wanted to be able to highlight a word or words in my text box, press the left mouse button, and then drag it from the text box.)

I don't know if I'm using the wrong search terms but I have searched the net for hours for information and can't find it anywhere!

If anyone could please point me in the right direction to find information on how to write a code to do this, it'd be truely appreciated.

Thanks so much for reading.
 
I tried to discover this years ago, but without success. I'm trying again now, with the same result. The code I have found doesn't work properly.

This is functionality so common that you'd expect it to be known everywhere, yet it remains a mystery!

Have you succeeded yet? If so, please let me know.
 
This goes deep into behaviour of OS standard controls, what you're trying to do with mouse conflicts with how text selections are done, and this happens before .Net gets the events. For Textbox the selection is reset before the MouseDown event is raised. Though it might be possible to use the windows messages, the RichTextBox has selections intact in MouseDown event, so you can use this control instead.

Here is the code sample I tested, it checks first for correct button and if any text is selected, if so gets the character index for mouse down location and compares this with the selection indexes. So if you mouse down on a selection the DoDragDrop is triggered, else mouse does standard selections.
VB.NET:
Private Sub RichTextBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RichTextBox1.MouseDown
    Dim box As RichTextBox = CType(sender, RichTextBox)
    If e.Button = Windows.Forms.MouseButtons.Left _
    AndAlso box.SelectionLength > 0 Then
        Dim ix As Integer = box.GetCharIndexFromPosition(e.Location)
        If ix >= box.SelectionStart _
        AndAlso ix - box.SelectionStart < box.SelectionLength Then
            box.DoDragDrop(box.SelectedText, DragDropEffects.Copy)
        End If
    End If
End Sub
 
Back
Top