Putting Strings in the List Box

After you've created the list box, the next step is to put text strings in it. You do this by sending messages to the list box window procedure using the SendMessage call. The text strings are generally referenced by an index number that starts at 0 for the topmost item. In the examples that follow, hwndList is the handle to the child window list box control, and wIndex is the index value.

In cases where you pass a text string in the SendMessage call, the lParam parameter is a far pointer to a null-terminated string. To avoid error messages during compilation, cast this pointer to a LONG. Note that when you cast a near pointer to a LONG, the C compiler will first cast the near pointer to a far pointer.

In most of these examples, the SendMessage call returns LB_ERRSPACE (defined as -2) if the window procedure runs out of available memory space to store the contents of the list box. SendMessage returns LB_ERR (-1) if an error occurs for other reasons and LB_OKAY (0) if the operation is successful. You can test SendMessage for a nonzero value to detect either of the two errors. The list box allocates global memory (outside your program's data segment) for the list box contents.

If you use the LBS_SORT style (or if you are placing strings in the list box in the order that you want them to appear), then the easiest way to fill up a list box is with the LB- ADDSTRING message:

SendMessage (hwndList, LB_ADDSTRING, 0, (LONG) szString) ;

If you do not use LBS_SORT, you can insert strings into your list box by specifying an index value with LB_INSERTSTRING:

SendMessage (hwndList, LB_INSERTSTRING, wIndex, (LONG) szString) ;

For instance, if wIndex is equal to 4, szString becomes the new string with an index value of 4—the fifth string from the top because counting starts at 0. Any strings below this point are pushed down. A wIndex value of -1 adds the string to the bottom. You can use LB_INSERTSTRING with list boxes that have the LBS_SORT style, but the list box contents will not be re-sorted. (You can also insert strings into a list box using the LB_DIR message, which is discussed in detail toward the end of this chapter.)

You can delete a string from the list box by specifying the index value with the LB_DELETESTRING message:

SendMessage (hwndList, LB_DELETESTRING, wIndex, 0L) ;

You can clear out the list box using LB_RESETCONTENT:

SendMessage (hwndList, LB_RESETCONTENT, 0, 0L) ;

The list box window procedure updates the display when an item is added to or deleted from the list box. If you have a number of strings to add or delete, you may want to temporarily inhibit this action by turning off the control's redraw flag:

SendMessage (hwndList, WM_SETREDRAW, FALSE, 0L) ;

After you've finished, you can turn the redraw flag back on:

SendMessage (hwndList, WM_SETREDRAW, TRUE, 0L) ;

A list box created with the LBS_NOREDRAW style begins with the redraw flag turned off.