Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleLet the user drag and drop text to a specific position in a TextBox in VB .NET
DescriptionThis example shows how to let the user drag and drop text to a specific position in a TextBox in VB .NET.
Keywordsdrag, drop, drag and drop, TextBox
CategoriesControls
 
When a drag moves over the TextBox, the DragOver event handler calls the TextBoxCursorPos function to see where the cursor is over the TextBox and it places the insertion position there.

If the user drops on the TextBox, the program inserts the dropped text at the current insertion position.

 
' If string data is available, allow a copy.
Private Sub TextBox1_DragOver(ByVal sender As Object, ByVal _
    e As System.Windows.Forms.DragEventArgs) Handles _
    TextBox1.DragOver
    If e.Data.GetDataPresent(DataFormats.StringFormat) Then
        ' Allow the drop.
        e.Effect = DragDropEffects.Copy

        ' Optionally move the cursor position so
        ' the user can see where the drop would happen.
        TextBox1.Select(TextBoxCursorPos(TextBox1, e.X, _
            e.Y), 0)
    Else
        ' Do not allow the drop.
        e.Effect = DragDropEffects.None
    End If
End Sub

' Drop the text into the TextBox.
Private Sub TextBox1_DragDrop(ByVal sender As Object, ByVal _
    e As System.Windows.Forms.DragEventArgs) Handles _
    TextBox1.DragDrop
    TextBox1.SelectedText = _
        e.Data.GetData(DataFormats.StringFormat)
End Sub
 
Function TextBoxCursorPos converts the mouse's coordinates from screen coordinates to the TextBox's coordinate system (both are in pixels). It then sends the EM_CHARFROMPOS message to the TextBox to get the position within the TextBox corresponding to the mouse's position. sends the Text
 
Private Const EM_CHARFROMPOS As Int32 = &HD7
Private Structure POINTAPI
    Public X As Integer
    Public Y As Integer
End Structure

Private Declare Function SendMessageLong Lib "user32" Alias _
    "SendMessageA" (ByVal hWnd As IntPtr, ByVal wMsg As _
    Int32, ByVal wParam As Int32, ByVal lParam As Int32) As _
    Long

' Return the character position under the mouse.
Public Function TextBoxCursorPos(ByVal txt As TextBox, _
    ByVal X As Single, ByVal Y As Single) As Long
    ' Convert screen coordinates into control coordinates.
    Dim pt As Point = TextBox1.PointToClient(New Point(X, _
        Y))

    ' Get the character number
    TextBoxCursorPos = SendMessageLong(txt.Handle, _
        EM_CHARFROMPOS, 0&, CLng(pt.X + pt.Y * &H10000)) _
        And &HFFFF&
End Function
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated