1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/listbox.cpp
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin (owner drawn stuff)
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "listbox.h"
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
26 #include "wx/listbox.h"
27 #include "wx/settings.h"
34 #include "wx/window.h"
35 #include "wx/msw/private.h"
39 #include "wx/dynarray.h"
43 #include "wx/ownerdrw.h"
46 #ifdef __GNUWIN32_OLD__
47 #include "wx/msw/gnuwin32/extra.h"
50 IMPLEMENT_DYNAMIC_CLASS(wxListBox
, wxControl
)
52 // ============================================================================
53 // list box item declaration and implementation
54 // ============================================================================
58 class wxListBoxItem
: public wxOwnerDrawn
61 wxListBoxItem(const wxString
& str
= wxEmptyString
);
64 wxListBoxItem::wxListBoxItem(const wxString
& str
) : wxOwnerDrawn(str
, FALSE
)
66 // no bitmaps/checkmarks
70 wxOwnerDrawn
*wxListBox::CreateLboxItem(size_t WXUNUSED(n
))
72 return new wxListBoxItem();
75 #endif //USE_OWNER_DRAWN
77 // ============================================================================
78 // list box control implementation
79 // ============================================================================
81 // ----------------------------------------------------------------------------
83 // ----------------------------------------------------------------------------
86 wxListBox::wxListBox()
92 bool wxListBox::Create(wxWindow
*parent
,
96 int n
, const wxString choices
[],
98 const wxValidator
& validator
,
107 SetValidator(validator
);
108 #endif // wxUSE_VALIDATORS
111 parent
->AddChild(this);
113 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
114 SetForegroundColour(parent
->GetForegroundColour());
116 m_windowId
= ( id
== -1 ) ? (int)NewControlId() : id
;
122 m_windowStyle
= style
;
124 DWORD wstyle
= WS_VISIBLE
| WS_CHILD
| WS_VSCROLL
| WS_TABSTOP
|
125 LBS_NOTIFY
| LBS_HASSTRINGS
;
127 wxASSERT_MSG( !(style
& wxLB_MULTIPLE
) || !(style
& wxLB_EXTENDED
),
128 _T("only one of listbox selection modes can be specified") );
130 if ( (m_windowStyle
& wxBORDER_MASK
) == wxBORDER_DEFAULT
)
131 m_windowStyle
|= wxBORDER_SUNKEN
;
133 if ( m_windowStyle
& wxCLIP_SIBLINGS
)
134 wstyle
|= WS_CLIPSIBLINGS
;
136 if (m_windowStyle
& wxLB_MULTIPLE
)
137 wstyle
|= LBS_MULTIPLESEL
;
138 else if (m_windowStyle
& wxLB_EXTENDED
)
139 wstyle
|= LBS_EXTENDEDSEL
;
141 if (m_windowStyle
& wxLB_ALWAYS_SB
)
142 wstyle
|= LBS_DISABLENOSCROLL
;
143 if (m_windowStyle
& wxLB_HSCROLL
)
144 wstyle
|= WS_HSCROLL
;
145 if (m_windowStyle
& wxLB_SORT
)
148 #if wxUSE_OWNER_DRAWN && !defined(__WXWINCE__)
149 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
150 // we don't support LBS_OWNERDRAWVARIABLE yet
151 wstyle
|= LBS_OWNERDRAWFIXED
;
155 // Without this style, you get unexpected heights, so e.g. constraint layout
156 // doesn't work properly
157 wstyle
|= LBS_NOINTEGRALHEIGHT
;
160 (void) MSWGetStyle(m_windowStyle
, & exStyle
) ;
162 m_hWnd
= (WXHWND
)::CreateWindowEx(exStyle
, wxT("LISTBOX"), NULL
,
165 (HWND
)parent
->GetHWND(), (HMENU
)m_windowId
,
166 wxGetInstance(), NULL
);
168 wxCHECK_MSG( m_hWnd
, FALSE
, wxT("Failed to create listbox") );
170 // Subclass again to catch messages
174 for (ui
= 0; ui
< (size_t)n
; ui
++) {
178 if ( (m_windowStyle
& wxLB_MULTIPLE
) == 0 )
179 SendMessage(GetHwnd(), LB_SETCURSEL
, 0, 0);
181 SetFont(parent
->GetFont());
183 SetSize(x
, y
, width
, height
);
188 wxListBox::~wxListBox()
193 void wxListBox::SetupColours()
195 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
196 SetForegroundColour(GetParent()->GetForegroundColour());
199 // ----------------------------------------------------------------------------
200 // implementation of wxListBoxBase methods
201 // ----------------------------------------------------------------------------
203 void wxListBox::DoSetFirstItem(int N
)
205 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
206 wxT("invalid index in wxListBox::SetFirstItem") );
208 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
211 void wxListBox::Delete(int N
)
213 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
214 wxT("invalid index in wxListBox::Delete") );
216 // for owner drawn objects, the data is used for storing wxOwnerDrawn
217 // pointers and we shouldn't touch it
218 #if !wxUSE_OWNER_DRAWN
219 if ( !(m_windowStyle
& wxLB_OWNERDRAW
) )
220 #endif // !wxUSE_OWNER_DRAWN
221 if ( HasClientObjectData() )
223 delete GetClientObject(N
);
226 SendMessage(GetHwnd(), LB_DELETESTRING
, N
, 0);
229 SetHorizontalExtent(wxEmptyString
);
232 int wxListBox::DoAppend(const wxString
& item
)
234 int index
= ListBox_AddString(GetHwnd(), item
);
237 #if wxUSE_OWNER_DRAWN
238 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
239 wxOwnerDrawn
*pNewItem
= CreateLboxItem(index
); // dummy argument
240 pNewItem
->SetName(item
);
241 m_aItems
.Insert(pNewItem
, index
);
242 ListBox_SetItemData(GetHwnd(), index
, pNewItem
);
243 pNewItem
->SetFont(GetFont());
245 #endif // wxUSE_OWNER_DRAWN
247 SetHorizontalExtent(item
);
252 void wxListBox::DoSetItems(const wxArrayString
& choices
, void** clientData
)
254 // avoid flicker - but don't need to do this for a hidden listbox
255 bool hideAndShow
= IsShown();
258 ShowWindow(GetHwnd(), SW_HIDE
);
261 ListBox_ResetContent(GetHwnd());
263 m_noItems
= choices
.GetCount();
265 for (i
= 0; i
< m_noItems
; i
++)
267 ListBox_AddString(GetHwnd(), choices
[i
]);
270 SetClientData(i
, clientData
[i
]);
274 #if wxUSE_OWNER_DRAWN
275 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
276 // first delete old items
277 WX_CLEAR_ARRAY(m_aItems
);
279 // then create new ones
280 for ( size_t ui
= 0; ui
< (size_t)m_noItems
; ui
++ ) {
281 wxOwnerDrawn
*pNewItem
= CreateLboxItem(ui
);
282 pNewItem
->SetName(choices
[ui
]);
283 m_aItems
.Add(pNewItem
);
284 ListBox_SetItemData(GetHwnd(), ui
, pNewItem
);
287 #endif // wxUSE_OWNER_DRAWN
289 SetHorizontalExtent();
293 // show the listbox back if we hid it
294 ShowWindow(GetHwnd(), SW_SHOW
);
298 int wxListBox::FindString(const wxString
& s
) const
300 int pos
= ListBox_FindStringExact(GetHwnd(), (WPARAM
)-1, s
);
307 void wxListBox::Clear()
311 ListBox_ResetContent(GetHwnd());
314 SetHorizontalExtent();
317 void wxListBox::Free()
319 #if wxUSE_OWNER_DRAWN
320 if ( m_windowStyle
& wxLB_OWNERDRAW
)
322 WX_CLEAR_ARRAY(m_aItems
);
325 #endif // wxUSE_OWNER_DRAWN
326 if ( HasClientObjectData() )
328 for ( size_t n
= 0; n
< (size_t)m_noItems
; n
++ )
330 delete GetClientObject(n
);
335 void wxListBox::SetSelection(int N
, bool select
)
337 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
338 wxT("invalid index in wxListBox::SetSelection") );
340 if ( HasMultipleSelection() )
342 SendMessage(GetHwnd(), LB_SETSEL
, select
, N
);
346 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
350 bool wxListBox::IsSelected(int N
) const
352 wxCHECK_MSG( N
>= 0 && N
< m_noItems
, FALSE
,
353 wxT("invalid index in wxListBox::Selected") );
355 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? FALSE
: TRUE
;
358 wxClientData
* wxListBox::DoGetItemClientObject(int n
) const
360 return (wxClientData
*)DoGetItemClientData(n
);
363 void *wxListBox::DoGetItemClientData(int n
) const
365 wxCHECK_MSG( n
>= 0 && n
< m_noItems
, NULL
,
366 wxT("invalid index in wxListBox::GetClientData") );
368 return (void *)SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
371 void wxListBox::DoSetItemClientObject(int n
, wxClientData
* clientData
)
373 DoSetItemClientData(n
, clientData
);
376 void wxListBox::DoSetItemClientData(int n
, void *clientData
)
378 wxCHECK_RET( n
>= 0 && n
< m_noItems
,
379 wxT("invalid index in wxListBox::SetClientData") );
381 #if wxUSE_OWNER_DRAWN
382 if ( m_windowStyle
& wxLB_OWNERDRAW
)
384 // client data must be pointer to wxOwnerDrawn, otherwise we would crash
385 // in OnMeasure/OnDraw.
386 wxFAIL_MSG(wxT("Can't use client data with owner-drawn listboxes"));
388 #endif // wxUSE_OWNER_DRAWN
390 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
391 wxLogDebug(wxT("LB_SETITEMDATA failed"));
394 // Return number of selections and an array of selected integers
395 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
399 if ( HasMultipleSelection() )
401 int countSel
= ListBox_GetSelCount(GetHwnd());
402 if ( countSel
== LB_ERR
)
404 wxLogDebug(_T("ListBox_GetSelCount failed"));
406 else if ( countSel
!= 0 )
408 int *selections
= new int[countSel
];
410 if ( ListBox_GetSelItems(GetHwnd(),
411 countSel
, selections
) == LB_ERR
)
413 wxLogDebug(wxT("ListBox_GetSelItems failed"));
418 aSelections
.Alloc(countSel
);
419 for ( int n
= 0; n
< countSel
; n
++ )
420 aSelections
.Add(selections
[n
]);
423 delete [] selections
;
428 else // single-selection listbox
430 if (ListBox_GetCurSel(GetHwnd()) > -1)
431 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
433 return aSelections
.Count();
437 // Get single selection, for single choice list items
438 int wxListBox::GetSelection() const
440 wxCHECK_MSG( !HasMultipleSelection(),
442 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
444 return ListBox_GetCurSel(GetHwnd());
447 // Find string for position
448 wxString
wxListBox::GetString(int N
) const
450 wxCHECK_MSG( N
>= 0 && N
< m_noItems
, wxEmptyString
,
451 wxT("invalid index in wxListBox::GetClientData") );
453 int len
= ListBox_GetTextLen(GetHwnd(), N
);
455 // +1 for terminating NUL
457 ListBox_GetText(GetHwnd(), N
, wxStringBuffer(result
, len
+ 1));
463 wxListBox::DoInsertItems(const wxArrayString
& items
, int pos
)
465 wxCHECK_RET( pos
>= 0 && pos
<= m_noItems
,
466 wxT("invalid index in wxListBox::InsertItems") );
468 int nItems
= items
.GetCount();
469 for ( int i
= 0; i
< nItems
; i
++ )
471 int idx
= ListBox_InsertString(GetHwnd(), i
+ pos
, items
[i
]);
473 #if wxUSE_OWNER_DRAWN
474 if ( m_windowStyle
& wxLB_OWNERDRAW
)
476 wxOwnerDrawn
*pNewItem
= CreateLboxItem(idx
);
477 pNewItem
->SetName(items
[i
]);
478 pNewItem
->SetFont(GetFont());
479 m_aItems
.Insert(pNewItem
, idx
);
481 ListBox_SetItemData(GetHwnd(), idx
, pNewItem
);
483 #endif // wxUSE_OWNER_DRAWN
488 SetHorizontalExtent();
491 void wxListBox::SetString(int N
, const wxString
& s
)
493 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
494 wxT("invalid index in wxListBox::SetString") );
496 // remember the state of the item
497 bool wasSelected
= IsSelected(N
);
499 void *oldData
= NULL
;
500 wxClientData
*oldObjData
= NULL
;
501 if ( m_clientDataItemsType
== wxClientData_Void
)
502 oldData
= GetClientData(N
);
503 else if ( m_clientDataItemsType
== wxClientData_Object
)
504 oldObjData
= GetClientObject(N
);
506 // delete and recreate it
507 SendMessage(GetHwnd(), LB_DELETESTRING
, N
, 0);
510 if ( N
== m_noItems
- 1 )
513 ListBox_InsertString(GetHwnd(), newN
, s
);
515 // restore the client data
517 SetClientData(N
, oldData
);
518 else if ( oldObjData
)
519 SetClientObject(N
, oldObjData
);
521 // we may have lost the selection
525 #if wxUSE_OWNER_DRAWN
526 if ( m_windowStyle
& wxLB_OWNERDRAW
)
528 // update item's text
529 m_aItems
[N
]->SetName(s
);
531 // reassign the item's data
532 ListBox_SetItemData(GetHwnd(), N
, m_aItems
[N
]);
534 #endif //USE_OWNER_DRAWN
537 int wxListBox::GetCount() const
542 // ----------------------------------------------------------------------------
544 // ----------------------------------------------------------------------------
546 // Windows-specific code to set the horizontal extent of the listbox, if
547 // necessary. If s is non-NULL, it's used to calculate the horizontal extent.
548 // Otherwise, all strings are used.
549 void wxListBox::SetHorizontalExtent(const wxString
& s
)
551 // Only necessary if we want a horizontal scrollbar
552 if (!(m_windowStyle
& wxHSCROLL
))
554 TEXTMETRIC lpTextMetric
;
558 int existingExtent
= (int)SendMessage(GetHwnd(), LB_GETHORIZONTALEXTENT
, 0, 0L);
559 HDC dc
= GetWindowDC(GetHwnd());
561 if (GetFont().Ok() && GetFont().GetResourceHandle())
562 oldFont
= (HFONT
) ::SelectObject(dc
, (HFONT
) GetFont().GetResourceHandle());
564 GetTextMetrics(dc
, &lpTextMetric
);
566 ::GetTextExtentPoint(dc
, (LPTSTR
) (const wxChar
*)s
, s
.Length(), &extentXY
);
567 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
570 ::SelectObject(dc
, oldFont
);
572 ReleaseDC(GetHwnd(), dc
);
573 if (extentX
> existingExtent
)
574 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(extentX
), 0L);
578 int largestExtent
= 0;
579 HDC dc
= GetWindowDC(GetHwnd());
581 if (GetFont().Ok() && GetFont().GetResourceHandle())
582 oldFont
= (HFONT
) ::SelectObject(dc
, (HFONT
) GetFont().GetResourceHandle());
584 GetTextMetrics(dc
, &lpTextMetric
);
586 // FIXME: buffer overflow!!
588 for (int i
= 0; i
< m_noItems
; i
++)
590 int len
= (int)SendMessage(GetHwnd(), LB_GETTEXT
, i
, (LPARAM
)buf
);
593 ::GetTextExtentPoint(dc
, buf
, len
, &extentXY
);
594 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
595 if (extentX
> largestExtent
)
596 largestExtent
= extentX
;
599 ::SelectObject(dc
, oldFont
);
601 ReleaseDC(GetHwnd(), dc
);
602 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
606 wxSize
wxListBox::DoGetBestSize() const
608 // find the widest string
611 for ( int i
= 0; i
< m_noItems
; i
++ )
613 wxString
str(GetString(i
));
614 GetTextExtent(str
, &wLine
, NULL
);
615 if ( wLine
> wListbox
)
619 // give it some reasonable default value if there are no strings in the
624 // the listbox should be slightly larger than the widest string
626 wxGetCharSize(GetHWND(), &cx
, &cy
, &GetFont());
630 // don't make the listbox too tall (limit height to 10 items) but don't
631 // make it too small neither
632 int hListbox
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
)*
633 wxMin(wxMax(m_noItems
, 3), 10);
635 return wxSize(wListbox
, hListbox
);
638 // ----------------------------------------------------------------------------
640 // ----------------------------------------------------------------------------
642 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
645 if ( param
== LBN_SELCHANGE
)
647 evtType
= wxEVT_COMMAND_LISTBOX_SELECTED
;
649 else if ( param
== LBN_DBLCLK
)
651 evtType
= wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
;
655 // some event we're not interested in
659 wxCommandEvent
event(evtType
, m_windowId
);
660 event
.SetEventObject( this );
662 // retrieve the affected item
663 int n
= SendMessage(GetHwnd(), LB_GETCARETINDEX
, 0, 0);
666 if ( HasClientObjectData() )
667 event
.SetClientObject( GetClientObject(n
) );
668 else if ( HasClientUntypedData() )
669 event
.SetClientData( GetClientData(n
) );
671 event
.SetString( GetString(n
) );
672 event
.SetExtraLong( HasMultipleSelection() ? IsSelected(n
) : TRUE
);
675 event
.m_commandInt
= n
;
677 return GetEventHandler()->ProcessEvent(event
);
680 // ----------------------------------------------------------------------------
681 // wxCheckListBox support
682 // ----------------------------------------------------------------------------
684 #if wxUSE_OWNER_DRAWN
689 // space beneath/above each row in pixels
690 // "standard" checklistbox use 1 here, some might prefer 2. 0 is ugly.
691 #define OWNER_DRAWN_LISTBOX_EXTRA_SPACE (1)
693 // the height is the same for all items
694 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
696 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
697 // message is not yet sent when we get here!
698 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
700 // only owner-drawn control should receive this message
701 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), FALSE
);
703 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
706 HDC hdc
= GetDC(NULL
);
708 HDC hdc
= CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0);
712 dc
.SetHDC((WXHDC
)hdc
);
713 dc
.SetFont(wxSystemSettings::GetFont(wxSYS_ANSI_VAR_FONT
));
715 pStruct
->itemHeight
= dc
.GetCharHeight() + 2*OWNER_DRAWN_LISTBOX_EXTRA_SPACE
;
716 pStruct
->itemWidth
= dc
.GetCharWidth();
725 // forward the message to the appropriate item
726 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
728 // only owner-drawn control should receive this message
729 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), FALSE
);
731 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
732 UINT itemID
= pStruct
->itemID
;
734 // the item may be -1 for an empty listbox
735 if ( itemID
== (UINT
)-1 )
738 long data
= ListBox_GetItemData(GetHwnd(), pStruct
->itemID
);
740 wxCHECK( data
&& (data
!= LB_ERR
), FALSE
);
742 wxListBoxItem
*pItem
= (wxListBoxItem
*)data
;
744 wxDCTemp
dc((WXHDC
)pStruct
->hDC
);
745 wxRect
rect(wxPoint(pStruct
->rcItem
.left
, pStruct
->rcItem
.top
),
746 wxPoint(pStruct
->rcItem
.right
, pStruct
->rcItem
.bottom
));
748 return pItem
->OnDrawItem(dc
, rect
,
749 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
750 (wxOwnerDrawn::wxODStatus
)pStruct
->itemState
);
753 #endif // wxUSE_OWNER_DRAWN
755 #endif // wxUSE_LISTBOX