|
|
Title | Let the user drag and drop text to a specific position in a TextBox |
Description | This example shows how to let the user drag and drop text to a specific position in a TextBox in Visual Basic 6. |
Keywords | drag, drop, drag and drop, TextBox |
Categories | Controls |
|
|
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.
|
|
' Display an appropriate drop picture.
Private Sub Text1_DragOver(Source As Control, X As Single, _
Y As Single, State As Integer)
If TypeOf Source Is Label Then
' Allow the drop.
Source.DragIcon = picDocument.Picture
' Optionally move the cursor position so
' the user can see where the drop would happen.
Text1.SelStart = TextBoxCursorPos(Text1, X, Y)
Text1.SelLength = 0
Else
' Do not allow the drop.
Source.DragIcon = Me.picNoDrop.Picture
End If
End Sub
Private Sub Text1_DragDrop(Source As Control, X As Single, _
Y As Single)
If Not (TypeOf Source Is Label) Then Exit Sub
' Move the insertion position to the mouse's location.
Text1.SelStart = TextBoxCursorPos(Text1, X, Y)
Text1.SelLength = 0
' Insert the dropped text.
Text1.SelText = Source.Caption
End Sub
|
|
Function TextBoxCursorPos converts the mouse's coordinates from twips to 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& = &HD7
Private Type POINTAPI
X As Long
Y As Long
End Type
Private Declare Function SendMessageLong Lib "user32" Alias _
"SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, _
ByVal wParam As Long, ByVal lParam As Long) 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 the position to pixels.
X = X \ Screen.TwipsPerPixelX
Y = Y \ Screen.TwipsPerPixelY
' Get the character number
TextBoxCursorPos = SendMessageLong(txt.hWnd, _
EM_CHARFROMPOS, 0&, CLng(X + Y * &H10000)) And _
&HFFFF&
End Function
|
|
|
|
|
|