ID Number: Q71069
1.00
WINDOWS
Summary:
Customers often ask how to quickly clear the contents of a list box
without clearing one item at a time. The following article shows how
to instantly clear the contents of a list box by sending the list box
a LB_RESETCONTENT message.
This information applies to Microsoft Visual Basic programming system
version 1.0 for Windows.
More Information:
No single command within Visual Basic will clear out the entries of a
list box, but a simple While Loop will, as follows:
Do While List1.ListCount > 0
List1.RemoveItem 0
Loop
If you want a single command to clear all list box entries at once,
you can use the SendMessage Windows API function. The arguments to
SendMessage with the LB_RESETCONTENT parameter are
SendMessage(hWnd%, wMsg%, wParam%, lParam&)
where:
hWnd% Identifies the window that is to receive the message
wMsg% The message to be sent (&H405)
wParam% Is not used (NULL)
lParam& Is not used (NULL)
Specifying wMsg% equal to &H405 removes all strings from the list box
and frees any memory allocated for those strings.
To get hWnd%, you must call the Windows API function GetFocus. This
method will return the handle to the control that currently has focus,
in this case the list box that you want to delete all items from.
The following code demonstrates how to delete entries from a list
box:
1. Create a list box called List1 on Form1.
2. Declare the following Windows API functions at the module level or
in the Global section of your code as follows:
Declare Function SendMessage% Lib "user" (ByVal hWnd%,_
ByVal wMsg%,_
ByVal wParam%,_
ByVal lParam&)
Declare Function GetFocus% Lib "user" ()
Declare Function PutFocus% Lib "user" Alias "SetFocus" (ByVal hWnd%)
(Note: Each Declare statement must be written on one line, leaving
out the underscore (_) line-continuation symbol shown above.)
3. Declare the following constants in the same section:
Const WM_USER = &H400
Const LB_RESETCONTENT = WM_USER + 5
4. Create a Sub within the (Declarations) section of the Code window
with the following code:
Sub ClearListBox (Ctrl As Control)
hWndOld% = GetFocus()
Ctrl.SetFocus
x = SendMessage(GetFocus(), LB_RESETCONTENT, 0, 0)
Suc% = PutFocus(hWndOld%)
End Sub
5. Within an event procedure, call ClearListBox with the name of the
list box as a parameter:
Sub Form_Click ()
ClearListBox List1
End Sub
6. Place some entries into the list box:
Sub Form_Load ()
For i = 1 To 10
List1.AddItem Format$(i) 'Put something into list box.
Next
End Sub
6. Run the program and click anywhere on Form1. This will clear out
the list box.
Reference(s):
"Programming Windows: the Microsoft Guide to Writing Applications for
Windows 3," by Charles Petzold, Microsoft Press, 1990
"Microsoft Windows Software Development Kit: Reference Volume 1"
version 3.0
WINSDK.HLP file shipped with Microsoft Windows 3.0 Software
Development Kit