How to Drop Item into Specified Location in VB List Box

ID Number: Q80187

1.00

WINDOWS

Summary:

You can drag an item and drop it into a list box by using the Visual

Basic TextHeight method and the Windows 3.0 API SendMessage function

to calculate where to drop the item.

This information applies to Microsoft Visual Basic programming system

version 1.0 for Windows.

More Information:

There is no standard way to determine in which position you are

dropping an item into a Visual Basic list box when you are performing

a drag and drop operation. You must calculate the position using the

TextHeight method and the Windows API SendMessage function with the

constant LB_GETTOPINDEX.

Using TextHeight, you can determine the height of each row of a list

box. Dividing this by the Y value that is passed as an argument in the

List_DragDrop event procedure, you can determine how many lines from

the top of the list box that the Drag.Icon is located over. The

SendMessage constant LB_GETTOPINDEX will give you the index of the

first visible item in the list box. Adding these two numbers will tell

you which index location where to insert the item in the list box.

To demonstrate an example of dropping items into the list box, do the

following:

1. Run Visual Basic, or from the File menu, choose New Project

(ALT, F, N) if Visual Basic is already running. Form1 will

be created by default.

2. Create a program with the following controls and related

properties:

Ctrl CtlName DragMode

---- ------- --------

Picture Picture1 Automatic

List List1 Manual

3. Add the following code to the global module:

'============= Global.Bas ===============

'NOTE: ALL DECLARE STATEMENTS MUST BE ON ONE LINE:

Declare Function SendMessage& Lib "User" (

ByVal hWnd%,

ByVal wMsg%,

ByVal wParam%,

lParam As Any)

Declare Function GetFocus Lib "User" () As Integer

Global Const LB_GETTOPINDEX = &H400 + 15

3. Add the following code to the DragDrop event procedure of List1:

'============== Form1.frm ==================

Sub List1_DragDrop (Source As Control, X As Single, Y As Single)

'get the first visible index in the list box

List1.SetFocus

ListHwnd = GetFocus()

TopI& = SendMessage(ListHwnd, LB_GETTOPINDEX, 0&, 0&)

ColumnHeight = TextHeight("A ")

InsertI& = Y \ ColumnHeight

If InsertI& <= List1.ListCount Then

List1.AddItem "This is inserted @" + Format$(InsertI&

+ TopI&, "0"), InsertI& + TopI&

Else

List1.AddItem "This is inserted"

End If

End Sub

4. From the Run menu, choose Start (ALT, R, S) to run the program.

Drag and drop the picture box over the list box and an item should be

added to the list box. An item will be added to the list box each time

you drag and drop the picture box over the list box.

Additional reference words: 1.00