devxlogo

Speed up Selecting Items in a MultiSelect List Box

Speed up Selecting Items in a MultiSelect List Box

Try this routine to select or deselect all items in a list box. Add a list box to your form with the MultiSelect property set to Simple or Extended, and add items to the list box:

 Sub ToggleSelectAll (lst As ListBox, ByVal bState As Integer)	Dim i As Integer	lst.Visible = False	'Avoid redraws for each item	For i = 0 To (lst.ListCount - 1)		lst.Selected(i) = bState	Next i	lst.Visible = TrueEnd Sub

This routine sets the list box’s Visible property to False to prevent the list box from repainting itself after each item is selected. This makes the routine more efficient. However, you can speed up this routine by using SendMessage instead of VB statements:

 Sub ToggleSelectAll (lst As ListBox, _	ByVal bState As Integer)	Dim i As Integer	Dim nRet As Long	lst.Visible = False	For i = 0 To lst.ListCount - 1		nRet = SendMessage(lst.hWnd, LB_SETSEL, bState, i)	Next i	lst.Visible = TrueEnd Sub

You can speed up this routine significantly by taking advantage of the fact that the LB_SETSEL message sets the state of all items in the list box at once if the index argument is -1. Because this approach uses a single call to SendMessage, you don’t need to worry about setting the list box’s Visible property to False to prevent multiple redraws:

 Sub ToggleSelectAll (lst As ListBox, _	ByVal bState As Integer)	Dim nRet As Long	nRet = SendMessage(lst.hWnd, LB_SETSEL, bState, -1)End Sub

Use these 16-bit declarations:

 Declare Function SendMessage Lib "User" ( _	ByVal hWnd As Integer, ByVal wMsg As Integer, _	ByVal wParam As Integer, ByVal lParam As Long) As LongGlobal Const WM_USER = &H400Global Const LB_SETSEL = (WM_USER + 6)

Or use these 32-bit declarations:

 Public Declare Function SendMessage Lib _	"User32" Alias "SendMessageA" ( _	ByVal hWnd As Long, ByVal wMsg As Integer, _	ByVal wParam As Long, ByVal lParam As Long) As LongPublic Const WM_USER = &H400Public Const LB_SETSEL = (WM_USER + 6)
See also  How to Avoid Money Transfer Scams  
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist