INF: Making a List Box Item Unavailable for Selection

ID Number: Q74792

3.00 3.10

WINDOWS

Summary:

In the Microsoft Windows graphical environment, an application can use

a list box to enumerate options. However, there are circumstances in

which one or more options may not be appropriate. The application can

change the appearance of items in a list box and prevent the user from

selecting one of these items by using the techniques discussed below.

More Information:

Changing the Appearance of a List Box Item

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

To dim (gray) a particular item in a list box, use an owner-draw list

box as follows:

1. Create a list box that has the LBS_OWNERDRAW and LBS_HASSTRINGS

styles.

2. Use the following code to process the WM_MEASUREITEM message:

case WM_MEASUREITEM:

((MEASUREITEMSTRUCT FAR *)(lParam))->itemHeight = wItemHeight;

break;

wItemHeight is the height of a character in the list box font.

3. Use the following code to process the WM_DRAWITEM message:

#define PHDC (pDIS->hDC)

#define PRC (pDIS->rcItem)

DRAWITEMSTRUCT FAR *pDIS;

...

case WM_DRAWITEM:

pDIS = (DRAWITEMSTRUCT FAR *)lParam;

SendMessage(pDIS->hwndItem, LB_GETTEXT, pDIS->itemID,

(LONG)(LPSTR)szBuff);

FillRect(PHDC, &PRC,

GetClassWord(pDIS->hwndItem, GCW_HBRBACKGROUND));

if ('!' == *szBuf) // this string is disabled

GrayString(PHDC, hGrayBrush, NULL, szBuf + 1, 0, 0, 0, 0, 0);

else

TextOut(PHDC, PRC.left, PRC.top, szBuf, lstrlen(szBuf));

if ((pDIS->itemState) & (ODS_FOCUS))

DrawFocusRect(PHDC, &PRC);

return TRUE;

Strings that start with "!" are displayed dimmed. The exclamation mark

character is not displayed.

Preventing Selection

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

To prevent a dimmed string from being selected, create the list box

with the LBS_NOTIFY style. Then use the following code in the list

box's parent window procedure to process the LBN_SELCHANGE

notification:

case WM_COMMAND:

switch (wParam)

{

...

case IDD_LISTBOX:

if (LBN_SELCHANGE == HIWORD(lParam))

{

idx = (int)SendDlgItemMessage(hDlg, wParam,

LB_GETCURSEL, 0, 0L);

SendDlgItemMessage(hDlg, wParam, LB_GETTEXT, idx,

(LONG)(LPSTR)szBuf);

if ('!' == *szBuf)

{

// Calculate an alternate index here

// (not shown in this example).

// Then set the index.

SendDlgItemMessage(hDlg, wParam, LB_SETCURSEL, idx, 0L);

}

}

break;

...

}

break;

When the user attempts to select a dimmed item, the alternate index

calculation moves the selection to an available item.

Additional reference words: 3.00 3.10 listbox