Partager via


CListBox::CharToItem

Called by the framework when the list box's parent window receives a WM_CHARTOITEM message from the list box.

virtual int CharToItem(
   UINT nKey,
   UINT nIndex 
);

Parameters

  • nKey
    The ANSI code of the character the user typed.

  • nIndex
    The current position of the list-box caret.

Return Value

Returns – 1 or – 2 for no further action or a nonnegative number to specify an index of a list-box item on which to perform the default action for the keystroke. The default implementation returns – 1.

Remarks

The WM_CHARTOITEM message is sent by the list box when it receives a WM_CHAR message, but only if the list box meets all of these criteria:

  • Is an owner-draw list box.

  • Does not have the LBS_HASSTRINGS style set.

  • Has at least one item.

You should never call this function yourself. Override this function to provide your own custom handling of keyboard messages.

In your override, you must return a value to tell the framework what action you performed. A return value of – 1 or – 2 indicates that you handled all aspects of selecting the item and requires no further action by the list box. Before returning – 1 or – 2, you could set the selection or move the caret or both. To set the selection, use SetCurSel or SetSel. To move the caret, use SetCaretIndex.

A return value of 0 or greater specifies the index of an item in the list box and indicates that the list box should perform the default action for the keystroke on the given item.

Example

// CMyODListBox is my owner-drawn list box derived from CListBox. This 
// example moves the caret down one item on a numeric key and up one item 
// on an alphabetic key. The list box control was created with the 
// following code:
//   m_myODListBox.Create(
//      WS_CHILD|WS_VISIBLE|WS_BORDER|WS_HSCROLL|WS_VSCROLL|
//      LBS_SORT|LBS_MULTIPLESEL|LBS_OWNERDRAWVARIABLE|LBS_WANTKEYBOARDINPUT,
//      CRect(10,250,200,450), pParentWnd, IDC_MYODLISTBOX);
//
int CMyODListBox::CharToItem(UINT nChar, UINT nIndex)
{
   // On a numeric key, move the caret up one item.
   if (isdigit(nChar) && (nIndex > 0))
   {
      SetCaretIndex(nIndex-1);
   }
   // On an alphabetic key, move the caret down one item.
   else if (isalpha(nChar) && (nIndex < (UINT)GetCount()))
   {
      SetCaretIndex(nIndex+1);
   }

   // Do not perform any default processing.
   return -1;
}

Requirements

Header: afxwin.h

See Also

Reference

CListBox Class

Hierarchy Chart

CListBox::VKeyToItem

CListBox::SetCurSel

CListBox::SetSel

CListBox::SetCaretIndex

WM_CHARTOITEM

Other Resources

CListBox Members