The SendMessage calls that carry out the tasks shown below usually return a value. If an error occurs, this value is set to LB_ERR (defined as -1). Note that the return value from SendMessage is normally a signed long (LONG), but the values are unsigned integers (WORD), so some casting is necessary.
After you've put some items into a list box, you can find out how many items are in the list box:
nCount = (WORD) SendMessage (hwndList, LB_GETCOUNT, 0, 0L) ;
Some of the other calls are different for single-selection and multiple-selection list boxes. Let's first look at single-selection list boxes.
Normally, you'll let a user select from a list box. But if you want to highlight a default selection, you can use:
SendMessage (hwndList, LB_SETCURSEL, nIndex, 0L) ;
Setting lParam to -1 in this call deselects all items.
You can also select an item based on its initial characters:
nIndex = (WORD) SendMessage (hwndList, LB_SELECTSTRING, wIndex,
(LONG) szSearchString) ;
The wIndex given as the wParam parameter to the SendMessage call is the index following which the search begins for an item with initial characters that match szSearchString. A wIndex value of -1 starts the search from the top. SendMessage returns the index of the selected item, or LB_ERR if no initial characters match szSearchString.
When you get a WM_COMMAND message from the list box (or at any other time), you can determine the index of the current selection using LB_GETCURSEL:
nIndex = (WORD) SendMessage (hwndList, LB_GETCURSEL, 0, 0L) ;
The nIndex value returned from the call is LB_ERR if no item is selected.
You can determine the length of any string in the list box:
nLength = (WORD) SendMessage (hwndList, LB_GETTEXTLEN, nIndex, 0L) ;
and copy the item into the text buffer:
nLength = (WORD) SendMessage (hwndList, LB_GETTEXT, nIndex,
(LONG) szBuffer) ;
In both cases, the nLength value returned from the call is the length of the string. The szBuffer array must be large enough for the length of the string and a terminating NULL. You may want to use LB_GETTEXTLEN to first allocate some local memory to hold the string (which you'll learn how to do in Chapter 8).
For a multiple-selection list box, you cannot use LB_SETCURSEL, LB_GETCURSEL, or LB_SELECTSTRING. Instead, you use LB_SETSEL to set the selection state of a particular item without affecting other items that may also be selected:
SendMessage (hwndList, LB_SETSEL, wParam, (LONG) wIndex) ;
The wParam parameter is nonzero to select and highlight the item and 0 to deselect it. If the lParam parameter is -1, all items are either selected or deselected. You can also determine the selection state of a particular item using:
wSelect = (WORD) SendMessage (hwndList, LB_GETSEL, wIndex, 0L) ;
where wSelect is set to nonzero if the item indexed by wIndex is selected and 0 if it is not.