Muokkaa

Jaa


CListBox Class

Provides the functionality of a Windows list box.

Syntax

class CListBox : public CWnd

Members

Public Constructors

Name Description
CListBox::CListBox Constructs a CListBox object.

Public Methods

Name Description
CListBox::AddString Adds a string to a list box.
CListBox::CharToItem Override to provide custom WM_CHAR handling for owner-draw list boxes which don't have strings.
CListBox::CompareItem Called by the framework to determine the position of a new item in a sorted owner-draw list box.
CListBox::Create Creates the Windows list box and attaches it to the CListBox object.
CListBox::DeleteItem Called by the framework when the user deletes an item from an owner-draw list box.
CListBox::DeleteString Deletes a string from a list box.
CListBox::Dir Adds filenames, drives, or both from the current directory to a list box.
CListBox::DrawItem Called by the framework when a visual aspect of an owner-draw list box changes.
CListBox::FindString Searches for a string in a list box.
CListBox::FindStringExact Finds the first list-box string that matches a specified string.
CListBox::GetAnchorIndex Retrieves the zero-based index of the current anchor item in a list box.
CListBox::GetCaretIndex Determines the index of the item that has the focus rectangle in a multiple-selection list box.
CListBox::GetCount Returns the number of strings in a list box.
CListBox::GetCurSel Returns the zero-based index of the currently selected string in a list box.
CListBox::GetHorizontalExtent Returns the width in pixels that a list box can be scrolled horizontally.
CListBox::GetItemData Returns a value associated with the list-box item.
CListBox::GetItemDataPtr Returns a pointer to a list-box item.
CListBox::GetItemHeight Determines the height of items in a list box.
CListBox::GetItemRect Returns the bounding rectangle of the list-box item as it is currently displayed.
CListBox::GetListBoxInfo Retrieves the number of items per column.
CListBox::GetLocale Retrieves the locale identifier for a list box.
CListBox::GetSel Returns the selection state of a list-box item.
CListBox::GetSelCount Returns the number of strings currently selected in a multiple-selection list box.
CListBox::GetSelItems Returns the indices of the strings currently selected in a list box.
CListBox::GetText Copies a list-box item into a buffer.
CListBox::GetTextLen Returns the length in bytes of a list-box item.
CListBox::GetTopIndex Returns the index of the first visible string in a list box.
CListBox::InitStorage Preallocates blocks of memory for list box items and strings.
CListBox::InsertString Inserts a string at a specific location in a list box.
CListBox::ItemFromPoint Returns the index of the list-box item nearest a point.
CListBox::MeasureItem Called by the framework when an owner-draw list box is created to determine list-box dimensions.
CListBox::ResetContent Clears all the entries from a list box.
CListBox::SelectString Searches for and selects a string in a single-selection list box.
CListBox::SelItemRange Selects or deselects a range of strings in a multiple-selection list box.
CListBox::SetAnchorIndex Sets the anchor in a multiple-selection list box to begin an extended selection.
CListBox::SetCaretIndex Sets the focus rectangle to the item at the specified index in a multiple-selection list box.
CListBox::SetColumnWidth Sets the column width of a multicolumn list box.
CListBox::SetCurSel Selects a list-box string.
CListBox::SetHorizontalExtent Sets the width in pixels that a list box can be scrolled horizontally.
CListBox::SetItemData Sets a value associated with the list-box item.
CListBox::SetItemDataPtr Sets a pointer to the list-box item.
CListBox::SetItemHeight Sets the height of items in a list box.
CListBox::SetLocale Sets the locale identifier for a list box.
CListBox::SetSel Selects or deselects a list-box item in a multiple-selection list box.
CListBox::SetTabStops Sets the tab-stop positions in a list box.
CListBox::SetTopIndex Sets the zero-based index of the first visible string in a list box.
CListBox::VKeyToItem Override to provide custom WM_KEYDOWN handling for list boxes with the LBS_WANTKEYBOARDINPUT style set.

Remarks

A list box displays a list of items, such as filenames, that the user can view and select.

In a single-selection list box, the user can select only one item. In a multiple-selection list box, a range of items can be selected. When the user selects an item, it is highlighted and the list box sends a notification message to the parent window.

You can create a list box either from a dialog template or directly in your code. To create it directly, construct the CListBox object, then call the Create member function to create the Windows list-box control and attach it to the CListBox object. To use a list box in a dialog template, declare a list-box variable in your dialog box class, then use DDX_Control in your dialog box class's DoDataExchange function to connect the member variable to the control. (this is done for you automatically when you add a control variable to your dialog box class.)

Construction can be a one-step process in a class derived from CListBox. Write a constructor for the derived class and call Create from within the constructor.

If you want to handle Windows notification messages sent by a list box to its parent (usually a class derived from CDialog), add a message-map entry and message-handler member function to the parent class for each message.

Each message-map entry takes the following form:

ON_Notification( id, memberFxn )

where id specifies the child window ID of the list-box control sending the notification and memberFxn is the name of the parent member function you have written to handle the notification.

The parent's function prototype is as follows:

afx_msg void memberFxn( );

Following is a list of potential message-map entries and a description of the cases in which they would be sent to the parent:

  • ON_LBN_DBLCLK The user double-clicks a string in a list box. Only a list box that has the LBS_NOTIFY style will send this notification message.

  • ON_LBN_ERRSPACE The list box cannot allocate enough memory to meet the request.

  • ON_LBN_KILLFOCUS The list box is losing the input focus.

  • ON_LBN_SELCANCEL The current list-box selection is canceled. This message is only sent when a list box has the LBS_NOTIFY style.

  • ON_LBN_SELCHANGE The selection in the list box has changed. This notification is not sent if the selection is changed by the CListBox::SetCurSel member function. This notification applies only to a list box that has the LBS_NOTIFY style. The LBN_SELCHANGE notification message is sent for a multiple-selection list box whenever the user presses an arrow key, even if the selection does not change.

  • ON_LBN_SETFOCUS The list box is receiving the input focus.

  • ON_WM_CHARTOITEM An owner-draw list box that has no strings receives a WM_CHAR message.

  • ON_WM_VKEYTOITEM A list box with the LBS_WANTKEYBOARDINPUT style receives a WM_KEYDOWN message.

If you create a CListBox object within a dialog box (through a dialog resource), the CListBox object is automatically destroyed when the user closes the dialog box.

If you create a CListBox object within a window, you may need to destroy the CListBox object. If you create the CListBox object on the stack, it is destroyed automatically. If you create the CListBox object on the heap by using the new function, you must call delete on the object to destroy it when the user closes the parent window.

If you allocate any memory in the CListBox object, override the CListBox destructor to dispose of the allocation.

Inheritance Hierarchy

CObject

CCmdTarget

CWnd

CListBox

Requirements

Header: afxwin.h

CListBox::AddString

Adds a string to a list box.

int AddString(LPCTSTR lpszItem);

Parameters

lpszItem
Points to the null-terminated string that is to be added.

Return Value

The zero-based index to the string in the list box. The return value is LB_ERR if an error occurs; the return value is LB_ERRSPACE if insufficient space is available to store the new string.

Remarks

If the list box was not created with the LBS_SORT style, the string is added to the end of the list. Otherwise, the string is inserted into the list, and the list is sorted. If the list box was created with the LBS_SORT style but not the LBS_HASSTRINGS style, the framework sorts the list by one or more calls to the CompareItem member function.

Use InsertString to insert a string into a specific location within the list box.

Example

// Add 10 items to the list box.
CString str;
for (int i = 0; i < 10; i++)
{
   str.Format(_T("item string %d"), i);
   m_myListBox.AddString(str);
}

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;
}

CListBox::CListBox

Constructs a CListBox object.

CListBox();

Remarks

You construct a CListBox object in two steps. First, call the constructor ClistBox and then call Create, which initializes the Windows list box and attaches it to the CListBox.

Example

// Declare a local CListBox object.
CListBox myListBox;

// Declare a dynamic CListBox object.
CListBox *pmyListBox = new CListBox;

CListBox::CompareItem

Called by the framework to determine the relative position of a new item in a sorted owner-draw list box.

virtual int CompareItem(LPCOMPAREITEMSTRUCT lpCompareItemStruct);

Parameters

lpCompareItemStruct
A long pointer to a COMPAREITEMSTRUCT structure.

Return Value

Indicates the relative position of the two items described in the COMPAREITEMSTRUCT structure. It may be any of the following values:

Value Meaning
-1 Item 1 sorts before item 2.
0 Item 1 and item 2 sort the same.
1 Item 1 sorts after item 2.

See CWnd::OnCompareItem for a description of the COMPAREITEMSTRUCT structure.

Remarks

By default, this member function does nothing. If you create an owner-draw list box with the LBS_SORT style, you must override this member function to assist the framework in sorting new items added to the list box.

Example

// CMyODListBox is my owner-drawn list box derived from CListBox. This
// example compares two items using _tcscmp to sort items in reverse
// alphabetical order. 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::CompareItem(LPCOMPAREITEMSTRUCT lpCompareItemStruct)
{
   ASSERT(lpCompareItemStruct->CtlType == ODT_LISTBOX);
   LPCTSTR lpszText1 = (LPCTSTR)lpCompareItemStruct->itemData1;
   ASSERT(lpszText1 != NULL);
   LPCTSTR lpszText2 = (LPCTSTR)lpCompareItemStruct->itemData2;
   ASSERT(lpszText2 != NULL);

   return _tcscmp(lpszText2, lpszText1);
}

CListBox::Create

Creates the Windows list box and attaches it to the CListBox object.

virtual BOOL Create(
    DWORD dwStyle,
    const RECT& rect,
    CWnd* pParentWnd,
    UINT nID);

Parameters

dwStyle
Specifies the style of the list box. Apply any combination of list-box styles to the box.

rect
Specifies the list-box size and position. Can be either a CRect object or a RECT structure.

pParentWnd
Specifies the list box's parent window (usually a CDialog object). It must not be NULL.

nID
Specifies the list box's control ID.

Return Value

Nonzero if successful; otherwise 0.

Remarks

You construct a CListBox object in two steps. First, call the constructor and then call Create, which initializes the Windows list box and attaches it to the CListBox object.

When Create executes, Windows sends the WM_NCCREATE, WM_CREATE, WM_NCCALCSIZE, and WM_GETMINMAXINFO messages to the list-box control.

These messages are handled by default by the OnNcCreate, OnCreate, OnNcCalcSize, and OnGetMinMaxInfo member functions in the CWnd base class. To extend the default message handling, derive a class from CListBox, add a message map to the new class, and override the preceding message-handler member functions. Override OnCreate, for example, to perform needed initialization for a new class.

Apply the following window styles to a list-box control.

  • WS_CHILD Always

  • WS_VISIBLE Usually

  • WS_DISABLED Rarely

  • WS_VSCROLL To add a vertical scroll bar

  • WS_HSCROLL To add a horizontal scroll bar

  • WS_GROUP To group controls

  • WS_TABSTOP To allow tabbing to this control

Example

// pParentWnd is a pointer to the parent window.
m_myListBox.Create(WS_CHILD | WS_VISIBLE | LBS_STANDARD | WS_HSCROLL,
                   CRect(10, 10, 200, 200), pParentWnd, IDC_MYLISTBOX);

CListBox::DeleteItem

Called by the framework when the user deletes an item from an owner-draw CListBox object or destroys the list box.

virtual void DeleteItem(LPDELETEITEMSTRUCT lpDeleteItemStruct);

Parameters

lpDeleteItemStruct
A long pointer to a Windows DELETEITEMSTRUCT structure that contains information about the deleted item.

Remarks

The default implementation of this function does nothing. Override this function to redraw an owner-draw list box as needed.

See CWnd::OnDeleteItem for a description of the DELETEITEMSTRUCT structure.

Example

// CMyODListBox is my owner-drawn list box derived from CListBox. This
// example simply frees the item's text. 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);
//
void CMyODListBox::DeleteItem(LPDELETEITEMSTRUCT lpDeleteItemStruct)
{
   ASSERT(lpDeleteItemStruct->CtlType == ODT_LISTBOX);
   LPVOID lpszText = (LPVOID)lpDeleteItemStruct->itemData;
   ASSERT(lpszText != NULL);

   free(lpszText);

   CListBox::DeleteItem(lpDeleteItemStruct);
}

CListBox::DeleteString

Deletes the item in position nIndex from the list box.

int DeleteString(UINT nIndex);

Parameters

nIndex
Specifies the zero-based index of the string to be deleted.

Return Value

A count of the strings remaining in the list. The return value is LB_ERR if nIndex specifies an index greater than the number of items in the list.

Remarks

All items following nIndex now move down one position. For example, if a list box contains two items, deleting the first item will cause the remaining item to now be in the first position. nIndex=0 for the item in the first position.

Example

// Delete every other item from the list box.
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   m_myListBox.DeleteString(i);
}

CListBox::Dir

Adds a list of filenames, drives, or both to a list box.

int Dir(
    UINT attr,
    LPCTSTR lpszWildCard);

Parameters

attr
Can be any combination of the enum values described in CFile::GetStatus, or any combination of the following values:

Value Meaning
0x0000 File can be read from or written to.
0x0001 File can be read from but not written to.
0x0002 File is hidden and does not appear in a directory listing.
0x0004 File is a system file.
0x0010 The name specified by lpszWildCard specifies a directory.
0x0020 File has been archived.
0x4000 Include all drives that match the name specified by lpszWildCard.
0x8000 Exclusive flag. If the exclusive flag is set, only files of the specified type are listed. Otherwise, files of the specified type are listed in addition to "normal" files.

lpszWildCard
Points to a file-specification string. The string can contain wildcards (for example, *.*).

Return Value

The zero-based index of the last filename added to the list. The return value is LB_ERR if an error occurs; the return value is LB_ERRSPACE if insufficient space is available to store the new strings.

Example

// Add all the files and directories in the windows directory.
TCHAR lpszWinPath[MAX_PATH], lpszOldPath[MAX_PATH];
::GetWindowsDirectory(lpszWinPath, MAX_PATH);

::GetCurrentDirectory(MAX_PATH, lpszOldPath);
::SetCurrentDirectory(lpszWinPath);

m_myListBox.ResetContent();
m_myListBox.Dir(DDL_READWRITE | DDL_DIRECTORY, _T("*.*"));

::SetCurrentDirectory(lpszOldPath);

CListBox::DrawItem

Called by the framework when a visual aspect of an owner-draw list box changes.

virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);

Parameters

lpDrawItemStruct
A long pointer to a DRAWITEMSTRUCT structure that contains information about the type of drawing required.

Remarks

The itemAction and itemState members of the DRAWITEMSTRUCT structure define the drawing action that is to be performed.

By default, this member function does nothing. Override this member function to implement drawing for an owner-draw CListBox object. The application should restore all graphics device interface (GDI) objects selected for the display context supplied in lpDrawItemStruct before this member function terminates.

See CWnd::OnDrawItem for a description of the DRAWITEMSTRUCT structure.

Example

// CMyODListBox is my owner-drawn list box derived from CListBox. This
// example draws an item's text centered vertically and horizontally. 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);
//
void CMyODListBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
   ASSERT(lpDrawItemStruct->CtlType == ODT_LISTBOX);
   LPCTSTR lpszText = (LPCTSTR)lpDrawItemStruct->itemData;
   ASSERT(lpszText != NULL);
   CDC dc;

   dc.Attach(lpDrawItemStruct->hDC);

   // Save these value to restore them when done drawing.
   COLORREF crOldTextColor = dc.GetTextColor();
   COLORREF crOldBkColor = dc.GetBkColor();

   // If this item is selected, set the background color
   // and the text color to appropriate values. Also, erase
   // rect by filling it with the background color.
   if ((lpDrawItemStruct->itemAction | ODA_SELECT) &&
       (lpDrawItemStruct->itemState & ODS_SELECTED))
   {
      dc.SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
      dc.SetBkColor(::GetSysColor(COLOR_HIGHLIGHT));
      dc.FillSolidRect(&lpDrawItemStruct->rcItem,
                       ::GetSysColor(COLOR_HIGHLIGHT));
   }
   else
   {
      dc.FillSolidRect(&lpDrawItemStruct->rcItem, crOldBkColor);
   }

   // If this item has the focus, draw a red frame around the
   // item's rect.
   if ((lpDrawItemStruct->itemAction | ODA_FOCUS) &&
       (lpDrawItemStruct->itemState & ODS_FOCUS))
   {
      CBrush br(RGB(255, 0, 0));
      dc.FrameRect(&lpDrawItemStruct->rcItem, &br);
   }

   // Draw the text.
   dc.DrawText(
       lpszText,
       (int)_tcslen(lpszText),
       &lpDrawItemStruct->rcItem,
       DT_CENTER | DT_SINGLELINE | DT_VCENTER);

   // Reset the background color and the text color back to their
   // original values.
   dc.SetTextColor(crOldTextColor);
   dc.SetBkColor(crOldBkColor);

   dc.Detach();
}

CListBox::FindString

Finds the first string in a list box that contains the specified prefix without changing the list-box selection.

int FindString(
    int nStartAfter,
    LPCTSTR lpszItem) const;

Parameters

nStartAfter
Contains the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nStartAfter. If nStartAfter is -1, the entire list box is searched from the beginning.

lpszItem
Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string may contain any combination of uppercase and lowercase letters.

Return Value

The zero-based index of the matching item, or LB_ERR if the search was unsuccessful.

Remarks

Use the SelectString member function to both find and select a string.

Example

// The string to match.
LPCTSTR lpszmyString = _T("item");

// Delete all items that begin with the specified string.
int nIndex = 0;
while ((nIndex = m_myListBox.FindString(nIndex, lpszmyString)) != LB_ERR)
{
   m_myListBox.DeleteString(nIndex);
}

CListBox::FindStringExact

Finds the first list-box string that matches the string specified in lpszFind.

int FindStringExact(
    int nIndexStart,
    LPCTSTR lpszFind) const;

Parameters

nIndexStart
Specifies the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nIndexStart. If nIndexStart is -1, the entire list box is searched from the beginning.

lpszFind
Points to the null-terminated string to search for. This string can contain a complete filename, including the extension. The search is not case sensitive, so the string can contain any combination of uppercase and lowercase letters.

Return Value

The index of the matching item, or LB_ERR if the search was unsuccessful.

Remarks

If the list box was created with an owner-draw style but without the LBS_HASSTRINGS style, the FindStringExact member function attempts to match the doubleword value against the value of lpszFind.

Example

// The string to match.
LPCTSTR lpszmyString = _T("item string 3");

// Delete all items that exactly match the specified string.
int nIndex = 0;
while ((nIndex = m_myListBox.FindStringExact(nIndex, lpszmyString)) != LB_ERR)
{
   m_myListBox.DeleteString(nIndex);
}

CListBox::GetAnchorIndex

Retrieves the zero-based index of the current anchor item in the list box.

int GetAnchorIndex() const;

Return Value

The index of the current anchor item, if successful; otherwise LB_ERR.

Remarks

In a multiple-selection list box, the anchor item is the first or last item in a block of contiguous selected items.

Example

See the example for CListBox::SetAnchorIndex.

CListBox::GetCaretIndex

Determines the index of the item that has the focus rectangle in a multiple-selection list box.

int GetCaretIndex() const;

Return Value

The zero-based index of the item that has the focus rectangle in a list box. If the list box is a single-selection list box, the return value is the index of the item that is selected, if any.

Remarks

The item may or may not be selected.

Example

See the example for CListBox::SetCaretIndex.

CListBox::GetCount

Retrieves the number of items in a list box.

int GetCount() const;

Return Value

The number of items in the list box, or LB_ERR if an error occurs.

Remarks

The returned count is one greater than the index value of the last item (the index is zero-based).

Example

// Add 10 items to the list box.
CString str;
for (int i = 0; i < 10; i++)
{
   str.Format(_T("item %d"), i);
   m_myListBox.AddString(str);
}

// Verify that 10 items were added to the list box.
ASSERT(m_myListBox.GetCount() == 10);

CListBox::GetCurSel

Retrieves the zero-based index of the currently selected item, if any, in a single-selection list box.

int GetCurSel() const;

Return Value

The zero-based index of the currently selected item if it is a single-selection list box. It is LB_ERR if no item is currently selected.

In a multiple-selection list box, the index of the item that has the focus.

Remarks

Do not call GetCurSel for a multiple-selection list box. Use CListBox::GetSelItems instead.

Example

// Select the next item of the currently selected one.
int nIndex = m_myListBox.GetCurSel();
int nCount = m_myListBox.GetCount();
if ((nIndex != LB_ERR) && (nCount > 1))
{
   if (++nIndex < nCount)
      m_myListBox.SetCurSel(nIndex);
   else
      m_myListBox.SetCurSel(0);
}

CListBox::GetHorizontalExtent

Retrieves from the list box the width in pixels by which it can be scrolled horizontally.

int GetHorizontalExtent() const;

Return Value

The scrollable width of the list box, in pixels.

Remarks

This is applicable only if the list box has a horizontal scroll bar.

Example

// Find the longest string in the list box.
CString str;
CSize sz;
int dx = 0;
CDC *pDC = m_myListBox.GetDC();
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   m_myListBox.GetText(i, str);
   sz = pDC->GetTextExtent(str);

   if (sz.cx > dx)
      dx = sz.cx;
}
m_myListBox.ReleaseDC(pDC);

// Set the horizontal extent only if the current extent is not large enough.
if (m_myListBox.GetHorizontalExtent() < dx)
{
   m_myListBox.SetHorizontalExtent(dx);
   ASSERT(m_myListBox.GetHorizontalExtent() == dx);
}

CListBox::GetItemData

Retrieves the application-supplied doubleword value associated with the specified list-box item.

DWORD_PTR GetItemData(int nIndex) const;

Parameters

nIndex
Specifies the zero-based index of the item in the list box.

Return Value

The value associated with the item, or LB_ERR if an error occurs.

Remarks

The doubleword value was the dwItemData parameter of a SetItemData call.

Example

// If any item's data is equal to zero then reset it to -1.
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   if (m_myListBox.GetItemData(i) == 0)
   {
      m_myListBox.SetItemData(i, (DWORD)-1);
   }
}

CListBox::GetItemDataPtr

Retrieves the application-supplied 32-bit value associated with the specified list-box item as a pointer (void *).

void* GetItemDataPtr(int nIndex) const;

Parameters

nIndex
Specifies the zero-based index of the item in the list box.

Return Value

Retrieves a pointer, or -1 if an error occurs.

Example

LPVOID lpmyPtr = pParentWnd;

// Check all the items in the list box; if an item's
// data pointer is equal to my pointer then reset it to NULL.
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   if (m_myListBox.GetItemDataPtr(i) == lpmyPtr)
   {
      m_myListBox.SetItemDataPtr(i, NULL);
   }
}

CListBox::GetItemHeight

Determines the height of items in a list box.

int GetItemHeight(int nIndex) const;

Parameters

nIndex
Specifies the zero-based index of the item in the list box. This parameter is used only if the list box has the LBS_OWNERDRAWVARIABLE style; otherwise, it should be set to 0.

Return Value

The height, in pixels, of the items in the list box. If the list box has the LBS_OWNERDRAWVARIABLE style, the return value is the height of the item specified by nIndex. If an error occurs, the return value is LB_ERR.

Example

// Set the height of every item so the item
// is completely visible.
CString str;
CSize sz;
CDC *pDC = m_myListBox.GetDC();
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   m_myListBox.GetText(i, str);
   sz = pDC->GetTextExtent(str);

   // Only want to set the item height if the current height
   // is not big enough.
   if (m_myListBox.GetItemHeight(i) < sz.cy)
      m_myListBox.SetItemHeight(i, sz.cy);
}
m_myListBox.ReleaseDC(pDC);

CListBox::GetItemRect

Retrieves the dimensions of the rectangle that bounds a list-box item as it is currently displayed in the list-box window.

int GetItemRect(
    int nIndex,
    LPRECT lpRect) const;

Parameters

nIndex
Specifies the zero-based index of the item.

lpRect
Specifies a long pointer to a RECT structure that receives the list-box client coordinates of the item.

Return Value

LB_ERR if an error occurs.

Example

// Dump all of the items bounds.
CString str;
RECT r;
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   m_myListBox.GetItemRect(i, &r);

   str.Format(_T("item %d: left = %d, top = %d, right = %d, ")
              _T("bottom = %d\r\n"),
              i,
              r.left,
              r.top,
              r.right,
              r.bottom);
   AFXDUMP(str);
}

CListBox::GetListBoxInfo

Retrieves the number of items per column.

DWORD GetListBoxInfo() const;

Return Value

Number of items per column of the CListBox object.

Remarks

This member function emulates the functionality of the LB_GETLISTBOXINFO message, as described in the Windows SDK.

CListBox::GetLocale

Retrieves the locale used by the list box.

LCID GetLocale() const;

Return Value

The locale identifier (LCID) value for the strings in the list box.

Remarks

The locale is used, for example, to determine the sort order of the strings in a sorted list box.

Example

See the example for CListBox::SetLocale.

CListBox::GetSel

Retrieves the selection state of an item.

int GetSel(int nIndex) const;

Parameters

nIndex
Specifies the zero-based index of the item.

Return Value

A positive number if the specified item is selected; otherwise, it is 0. The return value is LB_ERR if an error occurs.

Remarks

This member function works with both single- and multiple-selection list boxes.

To retrieve the index of the currently-selected list box item, use CListBox::GetCurSel.

Example

// Dump all of the items select state.
CString str;
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   str.Format(_T("item %d: select state is %s\r\n"),
              i,
              m_myListBox.GetSel(i) > 0 ? _T("true") : _T("false"));
   AFXDUMP(str);
}

CListBox::GetSelCount

Retrieves the total number of selected items in a multiple-selection list box.

int GetSelCount() const;

Return Value

The count of selected items in a list box. If the list box is a single-selection list box, the return value is LB_ERR.

Example

See the example for CListBox::GetSelItems.

CListBox::GetSelItems

Fills a buffer with an array of integers that specifies the item numbers of selected items in a multiple-selection list box.

int GetSelItems(
    int nMaxItems,
    LPINT rgIndex) const;

Parameters

nMaxItems
Specifies the maximum number of selected items whose item numbers are to be placed in the buffer.

rgIndex
Specifies a pointer to a buffer large enough for the number of integers specified by nMaxItems.

Return Value

The actual number of items placed in the buffer. If the list box is a single-selection list box, the return value is LB_ERR.

Example

// Get the indexes of all the selected items.
int nCount = m_myODListBox.GetSelCount();
CArray<int, int> aryListBoxSel;

aryListBoxSel.SetSize(nCount);
m_myODListBox.GetSelItems(nCount, aryListBoxSel.GetData());

// Dump the selection array.
AFXDUMP(aryListBoxSel);

CListBox::GetText

Gets a string from a list box.

int GetText(
    int nIndex,
    LPTSTR lpszBuffer) const;

void GetText(
    int nIndex,
    CString& rString) const;

Parameters

nIndex
Specifies the zero-based index of the string to be retrieved.

lpszBuffer
Points to the buffer that receives the string. The buffer must have sufficient space for the string and a terminating null character. The size of the string can be determined ahead of time by calling the GetTextLen member function.

rString
A reference to a CString object.

Return Value

The length (in bytes) of the string, excluding the terminating null character. If nIndex does not specify a valid index, the return value is LB_ERR.

Remarks

The second form of this member function fills a CString object with the string text.

Example

// Dump all of the items in the list box.
CString str, str2;
int n;
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   n = m_myListBox.GetTextLen(i);
   m_myListBox.GetText(i, str.GetBuffer(n));
   str.ReleaseBuffer();

   str2.Format(_T("item %d: %s\r\n"), i, str.GetBuffer(0));
   AFXDUMP(str2);
}

CListBox::GetTextLen

Gets the length of a string in a list-box item.

int GetTextLen(int nIndex) const;

Parameters

nIndex
Specifies the zero-based index of the string.

Return Value

The length of the string in characters, excluding the terminating null character. If nIndex does not specify a valid index, the return value is LB_ERR.

Example

See the example for CListBox::GetText.

CListBox::GetTopIndex

Retrieves the zero-based index of the first visible item in a list box.

int GetTopIndex() const;

Return Value

The zero-based index of the first visible item in a list box if successful, LB_ERR otherwise.

Remarks

Initially, item 0 is at the top of the list box, but if the list box is scrolled, another item may be at the top.

Example

// Want an item in the bottom half to be the first visible item.
int n = m_myListBox.GetCount() / 2;
if (m_myListBox.GetTopIndex() < n)
{
   m_myListBox.SetTopIndex(n);
   ASSERT(m_myListBox.GetTopIndex() == n);
}

CListBox::InitStorage

Allocates memory for storing list-box items.

int InitStorage(
    int nItems,
    UINT nBytes);

Parameters

nItems
Specifies the number of items to add.

nBytes
Specifies the amount of memory, in bytes, to allocate for item strings.

Return Value

If successful, the maximum number of items that the list box can store before a memory reallocation is needed, otherwise LB_ERRSPACE, meaning not enough memory is available.

Remarks

Call this function before adding a large number of items to a CListBox.

This function helps speed up the initialization of list boxes that have a large number of items (more than 100). It preallocates the specified amount of memory so that subsequent AddString, InsertString, and Dir functions take the shortest possible time. You can use estimates for the parameters. If you overestimate, some extra memory is allocated; if you underestimate, the normal allocation is used for items that exceed the preallocated amount.

Windows 95/98 only: The nItems parameter is limited to 16-bit values. This means list boxes cannot contain more than 32,767 items. Although the number of items is restricted, the total size of the items in a list box is limited only by available memory.

Example

// Initialize the storage of the list box to be 256 strings with
// about 10 characters per string, performance improvement.
int n = m_myListBox.InitStorage(256, 16 * sizeof(TCHAR));
ASSERT(n != LB_ERRSPACE);

// Add 256 items to the list box.
CString str;
for (int i = 0; i < 256; i++)
{
   str.Format(_T("item string %d"), i);
   m_myListBox.AddString(str);
}

CListBox::InsertString

Inserts a string into the list box.

int InsertString(
    int nIndex,
    LPCTSTR lpszItem);

Parameters

nIndex
Specifies the zero-based index of the position to insert the string. If this parameter is -1, the string is added to the end of the list.

lpszItem
Points to the null-terminated string that is to be inserted.

Return Value

The zero-based index of the position at which the string was inserted. The return value is LB_ERR if an error occurs; the return value is LB_ERRSPACE if insufficient space is available to store the new string.

Remarks

Unlike the AddString member function, InsertString does not cause a list with the LBS_SORT style to be sorted.

Example

// Insert items in between existing items.
CString str;
int n = m_myListBox.GetCount();
for (int i = 0; i < n; i++)
{
   str.Format(_T("item string %c"), (char)('A' + i));
   m_myListBox.InsertString(2 * i, str);
}

CListBox::ItemFromPoint

Determines the list-box item nearest the point specified in pt.

UINT ItemFromPoint(
    CPoint pt,
    BOOL& bOutside) const;

Parameters

pt
Point for which to find the nearest item, specified relative to the upper-left corner of the client area of the list box.

bOutside
Reference to a BOOL variable which will be set to TRUE if pt is outside the client area of the list box, FALSE if pt is inside the client area of the list box.

Return Value

The index of the nearest item to the point specified in pt.

Remarks

You could use this function to determine which list-box item the mouse cursor moves over.

Example

See the example for CListBox::SetAnchorIndex.

CListBox::MeasureItem

Called by the framework when a list box with an owner-draw style is created.

virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct);

Parameters

lpMeasureItemStruct
A long pointer to a MEASUREITEMSTRUCT structure.

Remarks

By default, this member function does nothing. Override this member function and fill in the MEASUREITEMSTRUCT structure to inform Windows of the list-box dimensions. If the list box is created with the LBS_OWNERDRAWVARIABLE style, the framework calls this member function for each item in the list box. Otherwise, this member is called only once.

For further information about using the LBS_OWNERDRAWFIXED style in an owner-draw list box created with the SubclassDlgItem member function of CWnd, see the discussion in Technical Note 14.

See CWnd::OnMeasureItem for a description of the MEASUREITEMSTRUCT structure.

Example

// CMyODListBox is my owner-drawn list box derived from CListBox. This
// example measures an item and sets the height of the item to twice the
// vertical extent of its text. 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);
//
void CMyODListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
   ASSERT(lpMeasureItemStruct->CtlType == ODT_LISTBOX);
   LPCTSTR lpszText = (LPCTSTR)lpMeasureItemStruct->itemData;
   ASSERT(lpszText != NULL);
   CSize sz;
   CDC *pDC = GetDC();

   sz = pDC->GetTextExtent(lpszText);

   ReleaseDC(pDC);

   lpMeasureItemStruct->itemHeight = 2 * sz.cy;
}

CListBox::ResetContent

Removes all items from a list box.

void ResetContent();

Example

// Delete all the items from the list box.
m_myListBox.ResetContent();
ASSERT(m_myListBox.GetCount() == 0);

CListBox::SelectString

Searches for a list-box item that matches the specified string, and if a matching item is found, it selects the item.

int SelectString(
    int nStartAfter,
    LPCTSTR lpszItem);

Parameters

nStartAfter
Contains the zero-based index of the item before the first item to be searched. When the search reaches the bottom of the list box, it continues from the top of the list box back to the item specified by nStartAfter. If nStartAfter is -1, the entire list box is searched from the beginning.

lpszItem
Points to the null-terminated string that contains the prefix to search for. The search is case independent, so this string may contain any combination of uppercase and lowercase letters.

Return Value

The index of the selected item if the search was successful. If the search was unsuccessful, the return value is LB_ERR and the current selection is not changed.

Remarks

The list box is scrolled, if necessary, to bring the selected item into view.

This member function cannot be used with a list box that has the LBS_MULTIPLESEL style.

An item is selected only if its initial characters (from the starting point) match the characters in the string specified by lpszItem.

Use the FindString member function to find a string without selecting the item.

Example

// The string to match.
LPCTSTR lpszmyString = _T("item 5");

// Select the item that begins with the specified string.
int nIndex = m_myListBox.SelectString(0, lpszmyString);
ASSERT(nIndex != LB_ERR);

CListBox::SelItemRange

Selects multiple consecutive items in a multiple-selection list box.

int SelItemRange(
    BOOL bSelect,
    int nFirstItem,
    int nLastItem);

Parameters

bSelect
Specifies how to set the selection. If bSelect is TRUE, the string is selected and highlighted; if FALSE, the highlight is removed and the string is no longer selected.

nFirstItem
Specifies the zero-based index of the first item to set.

nLastItem
Specifies the zero-based index of the last item to set.

Return Value

LB_ERR if an error occurs.

Remarks

Use this member function only with multiple-selection list boxes. If you need to select only one item in a multiple-selection list box — that is, if nFirstItem is equal to nLastItem — call the SetSel member function instead.

Example

// Select half of the items.
m_myODListBox.SelItemRange(TRUE, 0, m_myODListBox.GetCount() / 2);

CListBox::SetAnchorIndex

Sets the anchor in a multiple-selection list box to begin an extended selection.

void SetAnchorIndex(int nIndex);

Parameters

nIndex
Specifies the zero-based index of the list-box item that will be the anchor.

Remarks

In a multiple-selection list box, the anchor item is the first or last item in a block of contiguous selected items.

Example

void CMyODListBox::OnLButtonDown(UINT nFlags, CPoint point)
{
   BOOL bOutside = TRUE;
   UINT uItem = ItemFromPoint(point, bOutside);

   if (!bOutside)
   {
      // Set the anchor to be the middle item.
      SetAnchorIndex(uItem);
      ASSERT((UINT)GetAnchorIndex() == uItem);
   }

   CListBox::OnLButtonDown(nFlags, point);
}

CListBox::SetCaretIndex

Sets the focus rectangle to the item at the specified index in a multiple-selection list box.

int SetCaretIndex(
    int nIndex,
    BOOL bScroll = TRUE);

Parameters

nIndex
Specifies the zero-based index of the item to receive the focus rectangle in the list box.

bScroll
If this value is 0, the item is scrolled until it is fully visible. If this value is not 0, the item is scrolled until it is at least partially visible.

Return Value

LB_ERR if an error occurs.

Remarks

If the item is not visible, it is scrolled into view.

Example

// Set the caret to be the middle item.
m_myListBox.SetCaretIndex(m_myListBox.GetCount() / 2);
ASSERT(m_myListBox.GetCaretIndex() == m_myListBox.GetCount() / 2);

CListBox::SetColumnWidth

Sets the width in pixels of all columns in a multicolumn list box (created with the LBS_MULTICOLUMN style).

void SetColumnWidth(int cxWidth);

Parameters

cxWidth
Specifies the width in pixels of all columns.

Example

// Find the pixel width of the largest item.
CString str;
CSize   sz;
int     dx = 0;
CDC* pDC = myListBox.GetDC();
for (int i = 0; i < myListBox.GetCount(); i++)
{
   myListBox.GetText(i, str);
   sz = pDC->GetTextExtent(str);

   if (sz.cx > dx)
      dx = sz.cx;
}
myListBox.ReleaseDC(pDC);

// Set the column width of the first column to be one and 1/3 units
// of the largest string. 
myListBox.SetColumnWidth(dx * 4 / 3);

CListBox::SetCurSel

Selects a string and scrolls it into view, if necessary.

int SetCurSel(int nSelect);

Parameters

nSelect
Specifies the zero-based index of the string to be selected. If nSelect is -1, the list box is set to have no selection.

Return Value

LB_ERR if an error occurs.

Remarks

When the new string is selected, the list box removes the highlight from the previously selected string.

Use this member function only with single-selection list boxes.

To set or remove a selection in a multiple-selection list box, use CListBox::SetSel.

Example

// Select the last item in the list box.
int nCount = m_myListBox.GetCount();
if (nCount > 0)
   m_myListBox.SetCurSel(nCount - 1);

CListBox::SetHorizontalExtent

Sets the width, in pixels, by which a list box can be scrolled horizontally.

void SetHorizontalExtent(int cxExtent);

Parameters

cxExtent
Specifies the number of pixels by which the list box can be scrolled horizontally.

Remarks

If the size of the list box is smaller than this value, the horizontal scroll bar will horizontally scroll items in the list box. If the list box is as large or larger than this value, the horizontal scroll bar is hidden.

To respond to a call to SetHorizontalExtent, the list box must have been defined with the WS_HSCROLL style.

This member function is not useful for multicolumn list boxes. For multicolumn list boxes, call the SetColumnWidth member function.

Example

// Find the longest string in the list box.
CString str;
CSize sz;
int dx = 0;
TEXTMETRIC tm;
CDC *pDC = m_myListBox.GetDC();
CFont *pFont = m_myListBox.GetFont();

// Select the listbox font, save the old font
CFont *pOldFont = pDC->SelectObject(pFont);
// Get the text metrics for avg char width
pDC->GetTextMetrics(&tm);

for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   m_myListBox.GetText(i, str);
   sz = pDC->GetTextExtent(str);

   // Add the avg width to prevent clipping
   sz.cx += tm.tmAveCharWidth;

   if (sz.cx > dx)
      dx = sz.cx;
}
// Select the old font back into the DC
pDC->SelectObject(pOldFont);
m_myListBox.ReleaseDC(pDC);

// Set the horizontal extent so every character of all strings
// can be scrolled to.
m_myListBox.SetHorizontalExtent(dx);

CListBox::SetItemData

Sets a value associated with the specified item in a list box.

int SetItemData(
    int nIndex,
    DWORD_PTR dwItemData);

Parameters

nIndex
Specifies the zero-based index of the item.

dwItemData
Specifies the value to be associated with the item.

Return Value

LB_ERR if an error occurs.

Example

// Set the data of each item to be equal to its index.
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   m_myListBox.SetItemData(i, i);
}

CListBox::SetItemDataPtr

Sets the 32-bit value associated with the specified item in a list box to be the specified pointer ( void *).

int SetItemDataPtr(
    int nIndex,
    void* pData);

Parameters

nIndex
Specifies the zero-based index of the item.

pData
Specifies the pointer to be associated with the item.

Return Value

LB_ERR if an error occurs.

Remarks

This pointer remains valid for the life of the list box, even though the item's relative position within the list box might change as items are added or removed. Hence, the item's index within the box can change, but the pointer remains reliable.

Example

// Set the data pointer of each item to be NULL.
for (int i = 0; i < m_myListBox.GetCount(); i++)
{
   m_myListBox.SetItemDataPtr(i, NULL);
}

CListBox::SetItemHeight

Sets the height of items in a list box.

int SetItemHeight(
    int nIndex,
    UINT cyItemHeight);

Parameters

nIndex
Specifies the zero-based index of the item in the list box. This parameter is used only if the list box has the LBS_OWNERDRAWVARIABLE style; otherwise, it should be set to 0.

cyItemHeight
Specifies the height, in pixels, of the item.

Return Value

LB_ERR if the index or height is invalid.

Remarks

If the list box has the LBS_OWNERDRAWVARIABLE style, this function sets the height of the item specified by nIndex. Otherwise, this function sets the height of all items in the list box.

Example

// Set the height of every item to be the
// vertical size of the item's text extent.
CString str;
CSize sz;
CDC *pDC = myListBox.GetDC();
for (int i = 0; i < myListBox.GetCount(); i++)
{
   myListBox.GetText(i, str);
   sz = pDC->GetTextExtent(str);

   myListBox.SetItemHeight(i, sz.cy);
}
myListBox.ReleaseDC(pDC);

CListBox::SetLocale

Sets the locale identifier for this list box.

LCID SetLocale(LCID nNewLocale);

Parameters

nNewLocale
The new locale identifier (LCID) value to set for the list box.

Return Value

The previous locale identifier (LCID) value for this list box.

Remarks

If SetLocale is not called, the default locale is obtained from the system. This system default locale can be modified by using Control Panel's Regional (or International) application.

Example

// My LCID to use.
LCID mylcid = MAKELCID(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_MEXICAN),
                       SORT_DEFAULT);

// Force the list box to use my locale.
m_myListBox.SetLocale(mylcid);
ASSERT(m_myListBox.GetLocale() == mylcid);

CListBox::SetSel

Selects a string in a multiple-selection list box.

int SetSel(
    int nIndex,
    BOOL bSelect = TRUE);

Parameters

nIndex
Contains the zero-based index of the string to be set. If -1, the selection is added to or removed from all strings, depending on the value of bSelect.

bSelect
Specifies how to set the selection. If bSelect is TRUE, the string is selected and highlighted; if FALSE, the highlight is removed and the string is no longer selected. The specified string is selected and highlighted by default.

Return Value

LB_ERR if an error occurs.

Remarks

Use this member function only with multiple-selection list boxes.

To select an item from a single-selection list box, use CListBox::SetCurSel.

Example

// Select all of the items with an even index and
// deselect all others.
for (int i = 0; i < m_myODListBox.GetCount(); i++)
{
   m_myODListBox.SetSel(i, ((i % 2) == 0));
}

CListBox::SetTabStops

Sets the tab-stop positions in a list box.

void SetTabStops();
BOOL SetTabStops(const int& cxEachStop);

BOOL SetTabStops(
    int nTabStops,
    LPINT rgTabStops);

Parameters

cxEachStop
Tab stops are set at every cxEachStop dialog units. See rgTabStops for a description of a dialog unit.

nTabStops
Specifies the number of tab stops to have in the list box.

rgTabStops
Points to the first member of an array of integers containing the tab-stop positions in dialog units. A dialog unit is a horizontal or vertical distance. One horizontal dialog unit is equal to one-fourth of the current dialog base width unit, and one vertical dialog unit is equal to one-eighth of the current dialog base height unit. The dialog base units are computed based on the height and width of the current system font. The GetDialogBaseUnits Windows function returns the current dialog base units in pixels. The tab stops must be sorted in increasing order; back tabs are not allowed.

Return Value

Nonzero if all the tabs were set; otherwise 0.

Remarks

To set tab stops to the default size of 2 dialog units, call the parameterless version of this member function. To set tab stops to a size other than 2, call the version with the cxEachStop argument.

To set tab stops to an array of sizes, use the version with the rgTabStops and nTabStops arguments. A tab stop will be set for each value in rgTabStops, up to the number specified by nTabStops.

To respond to a call to the SetTabStops member function, the list box must have been created with the LBS_USETABSTOPS style.

Example

// Find the pixel width of the largest first substring.
CString str;
CSize sz;
int nIndex, dx = 0;
CDC *pDC = myListBox.GetDC();
for (int i = 0; i < myListBox.GetCount(); i++)
{
   myListBox.GetText(i, str);

   if ((nIndex = str.Find('\t')) != -1)
      str = str.Right(nIndex);

   sz = pDC->GetTextExtent(str);

   if (sz.cx > dx)
      dx = sz.cx;
}
myListBox.ReleaseDC(pDC);

// Set tab stops at every one and 1/3 units
// of the largest string.
// NOTE: Convert pixels to dialog units.
myListBox.SetTabStops((dx * 4 / 3 * 4) / LOWORD(::GetDialogBaseUnits()));

CListBox::SetTopIndex

Ensures that a particular list-box item is visible.

int SetTopIndex(int nIndex);

Parameters

nIndex
Specifies the zero-based index of the list-box item.

Return Value

Zero if successful, or LB_ERR if an error occurs.

Remarks

The system scrolls the list box until either the item specified by nIndex appears at the top of the list box or the maximum scroll range has been reached.

Example

// Set the first visible item in the list box to be the middle item
m_myListBox.SetTopIndex(m_myListBox.GetCount() / 2);

CListBox::VKeyToItem

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

virtual int VKeyToItem(
    UINT nKey,
    UINT nIndex);

Parameters

nKey
The virtual key code of the key the user pressed. For a list of standard virtual key codes, see Winuser.h

nIndex
The current position of the list-box caret.

Return Value

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

Remarks

The WM_VKEYTOITEM message is sent by the list box when it receives a WM_KEYDOWN message, but only if the list box meets both of the following:

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

You must return a value to tell the framework what action your override performed. A return value of - 2 indicates that the application handled all aspects of selecting the item and requires no further action by the list box. Before returning - 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 - 1 indicates that the list box should perform the default action in response to the keystroke.The default implementation returns - 1.

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 the down key and up one item
// on the up 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::VKeyToItem(UINT nKey, UINT nIndex)
{
   // On key up, move the caret up one item.
   if ((nKey == VK_UP) && (nIndex > 0))
   {
      SetCaretIndex(nIndex - 1);
   }
   // On key down, move the caret down one item.
   else if ((nKey == VK_DOWN) && (nIndex < (UINT)GetCount()))
   {
      SetCaretIndex(nIndex + 1);
   }

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

See also

MFC Sample CTRLTEST
CWnd Class
Hierarchy Chart
CWnd Class
CButton Class
CComboBox Class
CEdit Class
CScrollBar Class
CStatic Class