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"
47 #ifdef __GNUWIN32_OLD__
48 #include "wx/msw/gnuwin32/extra.h"
52 IMPLEMENT_DYNAMIC_CLASS(wxListBox
, wxControl
)
54 // ============================================================================
55 // list box item declaration and implementation
56 // ============================================================================
60 class wxListBoxItem
: public wxOwnerDrawn
63 wxListBoxItem(const wxString
& str
= wxEmptyString
);
66 wxListBoxItem::wxListBoxItem(const wxString
& str
) : wxOwnerDrawn(str
, FALSE
)
68 // no bitmaps/checkmarks
72 wxOwnerDrawn
*wxListBox::CreateLboxItem(size_t WXUNUSED(n
))
74 return new wxListBoxItem();
77 #endif //USE_OWNER_DRAWN
79 // ============================================================================
80 // list box control implementation
81 // ============================================================================
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
88 wxListBox::wxListBox()
94 bool wxListBox::Create(wxWindow
*parent
,
98 int n
, const wxString choices
[],
100 const wxValidator
& validator
,
101 const wxString
& name
)
109 SetValidator(validator
);
110 #endif // wxUSE_VALIDATORS
113 parent
->AddChild(this);
115 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
116 SetForegroundColour(parent
->GetForegroundColour());
118 m_windowId
= ( id
== -1 ) ? (int)NewControlId() : id
;
124 m_windowStyle
= style
;
126 DWORD wstyle
= WS_VISIBLE
| WS_CHILD
| WS_VSCROLL
| WS_TABSTOP
|
127 LBS_NOTIFY
| LBS_HASSTRINGS
;
129 wxASSERT_MSG( !(style
& wxLB_MULTIPLE
) || !(style
& wxLB_EXTENDED
),
130 _T("only one of listbox selection modes can be specified") );
132 if ( (m_windowStyle
& wxBORDER_MASK
) == wxBORDER_DEFAULT
)
133 m_windowStyle
|= wxBORDER_SUNKEN
;
135 if ( m_windowStyle
& wxCLIP_SIBLINGS
)
136 wstyle
|= WS_CLIPSIBLINGS
;
138 if (m_windowStyle
& wxLB_MULTIPLE
)
139 wstyle
|= LBS_MULTIPLESEL
;
140 else if (m_windowStyle
& wxLB_EXTENDED
)
141 wstyle
|= LBS_EXTENDEDSEL
;
143 if (m_windowStyle
& wxLB_ALWAYS_SB
)
144 wstyle
|= LBS_DISABLENOSCROLL
;
145 if (m_windowStyle
& wxLB_HSCROLL
)
146 wstyle
|= WS_HSCROLL
;
147 if (m_windowStyle
& wxLB_SORT
)
150 #if wxUSE_OWNER_DRAWN
151 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
152 // we don't support LBS_OWNERDRAWVARIABLE yet
153 wstyle
|= LBS_OWNERDRAWFIXED
;
157 // Without this style, you get unexpected heights, so e.g. constraint layout
158 // doesn't work properly
159 wstyle
|= LBS_NOINTEGRALHEIGHT
;
162 (void) MSWGetStyle(style
, & exStyle
) ;
164 m_hWnd
= (WXHWND
)::CreateWindowEx(exStyle
, wxT("LISTBOX"), NULL
,
167 (HWND
)parent
->GetHWND(), (HMENU
)m_windowId
,
168 wxGetInstance(), NULL
);
170 wxCHECK_MSG( m_hWnd
, FALSE
, wxT("Failed to create listbox") );
172 // Subclass again to catch messages
176 for (ui
= 0; ui
< (size_t)n
; ui
++) {
180 if ( (m_windowStyle
& wxLB_MULTIPLE
) == 0 )
181 SendMessage(GetHwnd(), LB_SETCURSEL
, 0, 0);
183 SetFont(parent
->GetFont());
185 SetSize(x
, y
, width
, height
);
190 wxListBox::~wxListBox()
195 void wxListBox::SetupColours()
197 SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
));
198 SetForegroundColour(GetParent()->GetForegroundColour());
201 // ----------------------------------------------------------------------------
202 // implementation of wxListBoxBase methods
203 // ----------------------------------------------------------------------------
205 void wxListBox::DoSetFirstItem(int N
)
207 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
208 wxT("invalid index in wxListBox::SetFirstItem") );
210 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
213 void wxListBox::Delete(int N
)
215 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
216 wxT("invalid index in wxListBox::Delete") );
218 // for owner drawn objects, the data is used for storing wxOwnerDrawn
219 // pointers and we shouldn't touch it
220 #if !wxUSE_OWNER_DRAWN
221 if ( !(m_windowStyle
& wxLB_OWNERDRAW
) )
222 #endif // !wxUSE_OWNER_DRAWN
223 if ( HasClientObjectData() )
225 delete GetClientObject(N
);
228 SendMessage(GetHwnd(), LB_DELETESTRING
, N
, 0);
231 SetHorizontalExtent(wxEmptyString
);
234 int wxListBox::DoAppend(const wxString
& item
)
236 int index
= ListBox_AddString(GetHwnd(), item
);
239 #if wxUSE_OWNER_DRAWN
240 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
241 wxOwnerDrawn
*pNewItem
= CreateLboxItem(index
); // dummy argument
242 pNewItem
->SetName(item
);
243 m_aItems
.Insert(pNewItem
, index
);
244 ListBox_SetItemData(GetHwnd(), index
, pNewItem
);
245 pNewItem
->SetFont(GetFont());
247 #endif // wxUSE_OWNER_DRAWN
249 SetHorizontalExtent(item
);
254 void wxListBox::DoSetItems(const wxArrayString
& choices
, void** clientData
)
256 // avoid flicker - but don't need to do this for a hidden listbox
257 bool hideAndShow
= IsShown();
260 ShowWindow(GetHwnd(), SW_HIDE
);
263 ListBox_ResetContent(GetHwnd());
265 m_noItems
= choices
.GetCount();
267 for (i
= 0; i
< m_noItems
; i
++)
269 ListBox_AddString(GetHwnd(), choices
[i
]);
272 SetClientData(i
, clientData
[i
]);
276 #if wxUSE_OWNER_DRAWN
277 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
278 // first delete old items
279 WX_CLEAR_ARRAY(m_aItems
);
281 // then create new ones
282 for ( size_t ui
= 0; ui
< (size_t)m_noItems
; ui
++ ) {
283 wxOwnerDrawn
*pNewItem
= CreateLboxItem(ui
);
284 pNewItem
->SetName(choices
[ui
]);
285 m_aItems
.Add(pNewItem
);
286 ListBox_SetItemData(GetHwnd(), ui
, pNewItem
);
289 #endif // wxUSE_OWNER_DRAWN
291 SetHorizontalExtent();
295 // show the listbox back if we hid it
296 ShowWindow(GetHwnd(), SW_SHOW
);
300 int wxListBox::FindString(const wxString
& s
) const
302 int pos
= ListBox_FindStringExact(GetHwnd(), (WPARAM
)-1, s
);
309 void wxListBox::Clear()
313 ListBox_ResetContent(GetHwnd());
316 SetHorizontalExtent();
319 void wxListBox::Free()
321 #if wxUSE_OWNER_DRAWN
322 if ( m_windowStyle
& wxLB_OWNERDRAW
)
324 WX_CLEAR_ARRAY(m_aItems
);
327 #endif // wxUSE_OWNER_DRAWN
328 if ( HasClientObjectData() )
330 for ( size_t n
= 0; n
< (size_t)m_noItems
; n
++ )
332 delete GetClientObject(n
);
337 void wxListBox::SetSelection(int N
, bool select
)
339 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
340 wxT("invalid index in wxListBox::SetSelection") );
342 if ( HasMultipleSelection() )
344 SendMessage(GetHwnd(), LB_SETSEL
, select
, N
);
348 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
352 bool wxListBox::IsSelected(int N
) const
354 wxCHECK_MSG( N
>= 0 && N
< m_noItems
, FALSE
,
355 wxT("invalid index in wxListBox::Selected") );
357 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? FALSE
: TRUE
;
360 wxClientData
* wxListBox::DoGetItemClientObject(int n
) const
362 return (wxClientData
*)DoGetItemClientData(n
);
365 void *wxListBox::DoGetItemClientData(int n
) const
367 wxCHECK_MSG( n
>= 0 && n
< m_noItems
, NULL
,
368 wxT("invalid index in wxListBox::GetClientData") );
370 return (void *)SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
373 void wxListBox::DoSetItemClientObject(int n
, wxClientData
* clientData
)
375 DoSetItemClientData(n
, clientData
);
378 void wxListBox::DoSetItemClientData(int n
, void *clientData
)
380 wxCHECK_RET( n
>= 0 && n
< m_noItems
,
381 wxT("invalid index in wxListBox::SetClientData") );
383 #if wxUSE_OWNER_DRAWN
384 if ( m_windowStyle
& wxLB_OWNERDRAW
)
386 // client data must be pointer to wxOwnerDrawn, otherwise we would crash
387 // in OnMeasure/OnDraw.
388 wxFAIL_MSG(wxT("Can't use client data with owner-drawn listboxes"));
390 #endif // wxUSE_OWNER_DRAWN
392 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
393 wxLogDebug(wxT("LB_SETITEMDATA failed"));
396 // Return number of selections and an array of selected integers
397 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
401 if ( HasMultipleSelection() )
403 int countSel
= ListBox_GetSelCount(GetHwnd());
404 if ( countSel
== LB_ERR
)
406 wxLogDebug(_T("ListBox_GetSelCount failed"));
408 else if ( countSel
!= 0 )
410 int *selections
= new int[countSel
];
412 if ( ListBox_GetSelItems(GetHwnd(),
413 countSel
, selections
) == LB_ERR
)
415 wxLogDebug(wxT("ListBox_GetSelItems failed"));
420 aSelections
.Alloc(countSel
);
421 for ( int n
= 0; n
< countSel
; n
++ )
422 aSelections
.Add(selections
[n
]);
425 delete [] selections
;
430 else // single-selection listbox
432 if (ListBox_GetCurSel(GetHwnd()) > -1)
433 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
435 return aSelections
.Count();
439 // Get single selection, for single choice list items
440 int wxListBox::GetSelection() const
442 wxCHECK_MSG( !HasMultipleSelection(),
444 wxT("GetSelection() can't be used with multiple-selection listboxes, use GetSelections() instead.") );
446 return ListBox_GetCurSel(GetHwnd());
449 // Find string for position
450 wxString
wxListBox::GetString(int N
) const
452 wxCHECK_MSG( N
>= 0 && N
< m_noItems
, wxEmptyString
,
453 wxT("invalid index in wxListBox::GetClientData") );
455 int len
= ListBox_GetTextLen(GetHwnd(), N
);
457 // +1 for terminating NUL
459 ListBox_GetText(GetHwnd(), N
, result
.GetWriteBuf(len
+ 1));
460 result
.UngetWriteBuf();
466 wxListBox::DoInsertItems(const wxArrayString
& items
, int pos
)
468 wxCHECK_RET( pos
>= 0 && pos
<= m_noItems
,
469 wxT("invalid index in wxListBox::InsertItems") );
471 int nItems
= items
.GetCount();
472 for ( int i
= 0; i
< nItems
; i
++ )
474 int idx
= ListBox_InsertString(GetHwnd(), i
+ pos
, items
[i
]);
476 #if wxUSE_OWNER_DRAWN
477 if ( m_windowStyle
& wxLB_OWNERDRAW
)
479 wxOwnerDrawn
*pNewItem
= CreateLboxItem(idx
);
480 pNewItem
->SetName(items
[i
]);
481 pNewItem
->SetFont(GetFont());
482 m_aItems
.Insert(pNewItem
, idx
);
484 ListBox_SetItemData(GetHwnd(), idx
, pNewItem
);
486 #endif // wxUSE_OWNER_DRAWN
491 SetHorizontalExtent();
494 void wxListBox::SetString(int N
, const wxString
& s
)
496 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
497 wxT("invalid index in wxListBox::SetString") );
499 // remember the state of the item
500 bool wasSelected
= IsSelected(N
);
502 void *oldData
= NULL
;
503 wxClientData
*oldObjData
= NULL
;
504 if ( m_clientDataItemsType
== wxClientData_Void
)
505 oldData
= GetClientData(N
);
506 else if ( m_clientDataItemsType
== wxClientData_Object
)
507 oldObjData
= GetClientObject(N
);
509 // delete and recreate it
510 SendMessage(GetHwnd(), LB_DELETESTRING
, N
, 0);
513 if ( N
== m_noItems
- 1 )
516 ListBox_InsertString(GetHwnd(), newN
, s
);
518 // restore the client data
520 SetClientData(N
, oldData
);
521 else if ( oldObjData
)
522 SetClientObject(N
, oldObjData
);
524 // we may have lost the selection
528 #if wxUSE_OWNER_DRAWN
529 if ( m_windowStyle
& wxLB_OWNERDRAW
)
531 // update item's text
532 m_aItems
[N
]->SetName(s
);
534 // reassign the item's data
535 ListBox_SetItemData(GetHwnd(), N
, m_aItems
[N
]);
537 #endif //USE_OWNER_DRAWN
540 int wxListBox::GetCount() const
545 // ----------------------------------------------------------------------------
547 // ----------------------------------------------------------------------------
549 // Windows-specific code to set the horizontal extent of the listbox, if
550 // necessary. If s is non-NULL, it's used to calculate the horizontal extent.
551 // Otherwise, all strings are used.
552 void wxListBox::SetHorizontalExtent(const wxString
& s
)
554 // Only necessary if we want a horizontal scrollbar
555 if (!(m_windowStyle
& wxHSCROLL
))
557 TEXTMETRIC lpTextMetric
;
561 int existingExtent
= (int)SendMessage(GetHwnd(), LB_GETHORIZONTALEXTENT
, 0, 0L);
562 HDC dc
= GetWindowDC(GetHwnd());
564 if (GetFont().Ok() && GetFont().GetResourceHandle())
565 oldFont
= (HFONT
) ::SelectObject(dc
, (HFONT
) GetFont().GetResourceHandle());
567 GetTextMetrics(dc
, &lpTextMetric
);
569 ::GetTextExtentPoint(dc
, (LPTSTR
) (const wxChar
*)s
, s
.Length(), &extentXY
);
570 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
573 ::SelectObject(dc
, oldFont
);
575 ReleaseDC(GetHwnd(), dc
);
576 if (extentX
> existingExtent
)
577 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(extentX
), 0L);
581 int largestExtent
= 0;
582 HDC dc
= GetWindowDC(GetHwnd());
584 if (GetFont().Ok() && GetFont().GetResourceHandle())
585 oldFont
= (HFONT
) ::SelectObject(dc
, (HFONT
) GetFont().GetResourceHandle());
587 GetTextMetrics(dc
, &lpTextMetric
);
589 for (i
= 0; i
< m_noItems
; i
++)
591 int len
= (int)SendMessage(GetHwnd(), LB_GETTEXT
, i
, (LONG
)wxBuffer
);
594 ::GetTextExtentPoint(dc
, (LPTSTR
)wxBuffer
, len
, &extentXY
);
595 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
596 if (extentX
> largestExtent
)
597 largestExtent
= extentX
;
600 ::SelectObject(dc
, oldFont
);
602 ReleaseDC(GetHwnd(), dc
);
603 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
607 wxSize
wxListBox::DoGetBestSize() const
609 // find the widest string
612 for ( int i
= 0; i
< m_noItems
; i
++ )
614 wxString
str(GetString(i
));
615 GetTextExtent(str
, &wLine
, NULL
);
616 if ( wLine
> wListbox
)
620 // give it some reasonable default value if there are no strings in the
625 // the listbox should be slightly larger than the widest string
627 wxGetCharSize(GetHWND(), &cx
, &cy
, &GetFont());
631 // don't make the listbox too tall (limit height to 10 items) but don't
632 // make it too small neither
633 int hListbox
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
)*
634 wxMin(wxMax(m_noItems
, 3), 10);
636 return wxSize(wListbox
, hListbox
);
639 // ----------------------------------------------------------------------------
641 // ----------------------------------------------------------------------------
643 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
646 if ( param
== LBN_SELCHANGE
)
648 evtType
= wxEVT_COMMAND_LISTBOX_SELECTED
;
650 else if ( param
== LBN_DBLCLK
)
652 evtType
= wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
;
656 // some event we're not interested in
660 wxCommandEvent
event(evtType
, m_windowId
);
661 event
.SetEventObject( this );
663 // retrieve the affected item
664 int n
= SendMessage(GetHwnd(), LB_GETCARETINDEX
, 0, 0);
667 if ( HasClientObjectData() )
668 event
.SetClientObject( GetClientObject(n
) );
669 else if ( HasClientUntypedData() )
670 event
.SetClientData( GetClientData(n
) );
672 event
.SetString( GetString(n
) );
673 event
.SetExtraLong( HasMultipleSelection() ? IsSelected(n
) : TRUE
);
676 event
.m_commandInt
= n
;
678 return GetEventHandler()->ProcessEvent(event
);
681 // ----------------------------------------------------------------------------
682 // wxCheckListBox support
683 // ----------------------------------------------------------------------------
685 #if wxUSE_OWNER_DRAWN
690 // space beneath/above each row in pixels
691 // "standard" checklistbox use 1 here, some might prefer 2. 0 is ugly.
692 #define OWNER_DRAWN_LISTBOX_EXTRA_SPACE (1)
694 // the height is the same for all items
695 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
697 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
698 // message is not yet sent when we get here!
699 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
701 // only owner-drawn control should receive this message
702 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), FALSE
);
704 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
706 HDC hdc
= CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0);
709 dc
.SetHDC((WXHDC
)hdc
);
710 dc
.SetFont(wxSystemSettings::GetFont(wxSYS_ANSI_VAR_FONT
));
712 pStruct
->itemHeight
= dc
.GetCharHeight() + 2*OWNER_DRAWN_LISTBOX_EXTRA_SPACE
;
713 pStruct
->itemWidth
= dc
.GetCharWidth();
722 // forward the message to the appropriate item
723 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
725 // only owner-drawn control should receive this message
726 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), FALSE
);
728 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
729 UINT itemID
= pStruct
->itemID
;
731 // the item may be -1 for an empty listbox
732 if ( itemID
== (UINT
)-1 )
735 long data
= ListBox_GetItemData(GetHwnd(), pStruct
->itemID
);
737 wxCHECK( data
&& (data
!= LB_ERR
), FALSE
);
739 wxListBoxItem
*pItem
= (wxListBoxItem
*)data
;
741 wxDCTemp
dc((WXHDC
)pStruct
->hDC
);
742 wxRect
rect(wxPoint(pStruct
->rcItem
.left
, pStruct
->rcItem
.top
),
743 wxPoint(pStruct
->rcItem
.right
, pStruct
->rcItem
.bottom
));
745 return pItem
->OnDrawItem(dc
, rect
,
746 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
747 (wxOwnerDrawn::wxODStatus
)pStruct
->itemState
);
750 #endif // wxUSE_OWNER_DRAWN
752 #endif // wxUSE_LISTBOX