1 ///////////////////////////////////////////////////////////////////////////////
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin (owner drawn stuff)
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows license
10 ///////////////////////////////////////////////////////////////////////////////
13 #pragma implementation "listbox.h"
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
23 #include "wx/window.h"
24 #include "wx/msw/private.h"
27 #include "wx/listbox.h"
28 #include "wx/settings.h"
38 #if defined(GetWindowStyle)
43 #include "wx/dynarray.h"
47 #include "wx/ownerdrw.h"
51 #if defined(__GNUWIN32__)
52 #ifndef wxUSE_NORLANDER_HEADERS
53 #include <wx/msw/gnuwin32/extra.h>
59 #ifndef ListBox_SetItemData
60 #define ListBox_SetItemData(hwndCtl, index, data) \
61 ((int)(DWORD)SendMessage((hwndCtl), LB_SETITEMDATA, (WPARAM)(int)(index), (LPARAM)(data)))
63 #ifndef ListBox_GetHorizontalExtent
64 #define ListBox_GetHorizontalExtent(hwndCtl) \
65 ((int)(DWORD)SendMessage((hwndCtl), LB_GETHORIZONTALEXTENT, 0L, 0L))
67 #ifndef ListBox_GetSelCount
68 #define ListBox_GetSelCount(hwndCtl) \
69 ((int)(DWORD)SendMessage((hwndCtl), LB_GETSELCOUNT, 0L, 0L))
71 #ifndef ListBox_GetSelItems
72 #define ListBox_GetSelItems(hwndCtl, cItems, lpItems) \
73 ((int)(DWORD)SendMessage((hwndCtl), LB_GETSELITEMS, (WPARAM)(int)(cItems), (LPARAM)(int *)(lpItems)))
75 #ifndef ListBox_GetTextLen
76 #define ListBox_GetTextLen(hwndCtl, index) \
77 ((int)(DWORD)SendMessage((hwndCtl), LB_GETTEXTLEN, (WPARAM)(int)(index), 0L))
79 #ifndef ListBox_GetText
80 #define ListBox_GetText(hwndCtl, index, lpszBuffer) \
81 ((int)(DWORD)SendMessage((hwndCtl), LB_GETTEXT, (WPARAM)(int)(index), (LPARAM)(LPCTSTR)(lpszBuffer)))
85 #if !USE_SHARED_LIBRARY
86 IMPLEMENT_DYNAMIC_CLASS(wxListBox
, wxControl
)
89 // ============================================================================
90 // list box item declaration and implementation
91 // ============================================================================
95 class wxListBoxItem
: public wxOwnerDrawn
98 wxListBoxItem(const wxString
& str
= "");
101 wxListBoxItem::wxListBoxItem(const wxString
& str
) : wxOwnerDrawn(str
, FALSE
)
103 // no bitmaps/checkmarks
107 wxOwnerDrawn
*wxListBox::CreateItem(size_t n
)
109 return new wxListBoxItem();
112 #endif //USE_OWNER_DRAWN
114 // ============================================================================
115 // list box control implementation
116 // ============================================================================
118 // ----------------------------------------------------------------------------
120 // ----------------------------------------------------------------------------
123 wxListBox::wxListBox()
129 bool wxListBox::Create(wxWindow
*parent
,
133 int n
, const wxString choices
[],
135 const wxValidator
& validator
,
136 const wxString
& name
)
143 SetValidator(validator
);
146 parent
->AddChild(this);
148 wxSystemSettings settings
;
149 SetBackgroundColour(settings
.GetSystemColour(wxSYS_COLOUR_WINDOW
));
150 SetForegroundColour(parent
->GetForegroundColour());
152 m_windowId
= ( id
== -1 ) ? (int)NewControlId() : id
;
158 m_windowStyle
= style
;
160 DWORD wstyle
= WS_VISIBLE
| WS_VSCROLL
| WS_TABSTOP
|
161 LBS_NOTIFY
| LBS_HASSTRINGS
;
162 if (m_windowStyle
& wxLB_MULTIPLE
)
163 wstyle
|= LBS_MULTIPLESEL
;
164 else if (m_windowStyle
& wxLB_EXTENDED
)
165 wstyle
|= LBS_EXTENDEDSEL
;
167 if (m_windowStyle
& wxLB_ALWAYS_SB
)
168 wstyle
|= LBS_DISABLENOSCROLL
;
169 if (m_windowStyle
& wxLB_HSCROLL
)
170 wstyle
|= WS_HSCROLL
;
171 if (m_windowStyle
& wxLB_SORT
)
174 #if wxUSE_OWNER_DRAWN
175 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
176 // we don't support LBS_OWNERDRAWVARIABLE yet
177 wstyle
|= LBS_OWNERDRAWFIXED
;
181 // Without this style, you get unexpected heights, so e.g. constraint layout
182 // doesn't work properly
183 wstyle
|= LBS_NOINTEGRALHEIGHT
;
186 WXDWORD exStyle
= Determine3DEffects(WS_EX_CLIENTEDGE
, &want3D
);
188 // Even with extended styles, need to combine with WS_BORDER for them to
190 if ( want3D
|| wxStyleHasBorder(m_windowStyle
) )
195 m_hWnd
= (WXHWND
)::CreateWindowEx(exStyle
, wxT("LISTBOX"), NULL
,
198 (HWND
)parent
->GetHWND(), (HMENU
)m_windowId
,
199 wxGetInstance(), NULL
);
201 wxCHECK_MSG( m_hWnd
, FALSE
, wxT("Failed to create listbox") );
206 Ctl3dSubclassCtl(GetHwnd());
211 // Subclass again to catch messages
215 for (ui
= 0; ui
< (size_t)n
; ui
++) {
219 if ( (m_windowStyle
& wxLB_MULTIPLE
) == 0 )
220 SendMessage(GetHwnd(), LB_SETCURSEL
, 0, 0);
222 SetFont(parent
->GetFont());
224 SetSize(x
, y
, width
, height
);
231 wxListBox::~wxListBox()
233 #if wxUSE_OWNER_DRAWN
234 size_t uiCount
= m_aItems
.Count();
235 while ( uiCount
-- != 0 ) {
236 delete m_aItems
[uiCount
];
238 #endif // wxUSE_OWNER_DRAWN
241 void wxListBox::SetupColours()
243 SetBackgroundColour(wxSystemSettings::GetSystemColour(wxSYS_COLOUR_WINDOW
));
244 SetForegroundColour(GetParent()->GetForegroundColour());
247 // ----------------------------------------------------------------------------
248 // implementation of wxListBoxBase methods
249 // ----------------------------------------------------------------------------
251 void wxListBox::DoSetFirstItem(int N
)
253 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
254 wxT("invalid index in wxListBox::SetFirstItem") );
256 SendMessage(GetHwnd(), LB_SETTOPINDEX
, (WPARAM
)N
, (LPARAM
)0);
259 void wxListBox::Delete(int N
)
261 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
262 wxT("invalid index in wxListBox::Delete") );
264 SendMessage(GetHwnd(), LB_DELETESTRING
, N
, 0);
267 SetHorizontalExtent("");
270 int wxListBox::DoAppend(const wxString
& item
)
272 int index
= ListBox_AddString(GetHwnd(), item
);
275 #if wxUSE_OWNER_DRAWN
276 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
277 wxOwnerDrawn
*pNewItem
= CreateItem(index
); // dummy argument
278 pNewItem
->SetName(item
);
279 m_aItems
.Add(pNewItem
);
280 ListBox_SetItemData(GetHwnd(), index
, pNewItem
);
284 SetHorizontalExtent(item
);
289 void wxListBox::DoSetItems(const wxArrayString
& choices
, void** clientData
)
291 ShowWindow(GetHwnd(), SW_HIDE
);
293 ListBox_ResetContent(GetHwnd());
295 m_noItems
= choices
.GetCount();
297 for (i
= 0; i
< m_noItems
; i
++)
299 ListBox_AddString(GetHwnd(), choices
[i
]);
302 #if wxUSE_OWNER_DRAWN
303 wxASSERT_MSG(clientData
[ui
] == NULL
,
304 wxT("Can't use client data with owner-drawn listboxes"));
305 #else // !wxUSE_OWNER_DRAWN
306 ListBox_SetItemData(GetHwnd(), i
, clientData
[i
]);
307 #endif // wxUSE_OWNER_DRAWN/!wxUSE_OWNER_DRAWN
311 #if wxUSE_OWNER_DRAWN
312 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
313 // first delete old items
314 size_t ui
= m_aItems
.Count();
315 while ( ui
-- != 0 ) {
320 // then create new ones
321 for ( ui
= 0; ui
< (size_t)m_noItems
; ui
++ ) {
322 wxOwnerDrawn
*pNewItem
= CreateItem(ui
);
323 pNewItem
->SetName(choices
[ui
]);
324 m_aItems
.Add(pNewItem
);
325 ListBox_SetItemData(GetHwnd(), ui
, pNewItem
);
328 #endif // wxUSE_OWNER_DRAWN
330 SetHorizontalExtent();
332 ShowWindow(GetHwnd(), SW_SHOW
);
335 int wxListBox::FindString(const wxString
& s
) const
337 int pos
= ListBox_FindStringExact(GetHwnd(), (WPARAM
)-1, s
);
344 void wxListBox::Clear()
346 ListBox_ResetContent(GetHwnd());
348 #if wxUSE_OWNER_DRAWN
349 size_t uiCount
= m_aItems
.Count();
350 while ( uiCount
-- != 0 ) {
351 delete m_aItems
[uiCount
];
355 #endif // wxUSE_OWNER_DRAWN
358 SetHorizontalExtent();
361 void wxListBox::SetSelection(int N
, bool select
)
363 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
364 wxT("invalid index in wxListBox::SetSelection") );
366 if ( HasMultipleSelection() )
368 SendMessage(GetHwnd(), LB_SETSEL
, select
, N
);
372 SendMessage(GetHwnd(), LB_SETCURSEL
, select
? N
: -1, 0);
376 bool wxListBox::IsSelected(int N
) const
378 wxCHECK_MSG( N
>= 0 && N
< m_noItems
, FALSE
,
379 wxT("invalid index in wxListBox::Selected") );
381 return SendMessage(GetHwnd(), LB_GETSEL
, N
, 0) == 0 ? FALSE
: TRUE
;
384 wxClientData
* wxListBox::DoGetClientObject(int n
) const
386 return (wxClientData
*)DoGetClientData(n
);
389 void *wxListBox::DoGetClientData(int n
) const
391 wxCHECK_MSG( n
>= 0 && n
< m_noItems
, NULL
,
392 wxT("invalid index in wxListBox::GetClientData") );
394 return (void *)SendMessage(GetHwnd(), LB_GETITEMDATA
, n
, 0);
397 void wxListBox::DoSetClientObject(int n
, wxClientData
* clientData
)
399 DoSetClientData(n
, clientData
);
402 void wxListBox::DoSetClientData(int n
, void *clientData
)
404 wxCHECK_RET( n
>= 0 && n
< m_noItems
,
405 wxT("invalid index in wxListBox::SetClientData") );
407 #if wxUSE_OWNER_DRAWN
408 if ( m_windowStyle
& wxLB_OWNERDRAW
)
410 // client data must be pointer to wxOwnerDrawn, otherwise we would crash
411 // in OnMeasure/OnDraw.
412 wxFAIL_MSG(wxT("Can't use client data with owner-drawn listboxes"));
414 #endif // wxUSE_OWNER_DRAWN
416 if ( ListBox_SetItemData(GetHwnd(), n
, clientData
) == LB_ERR
)
417 wxLogDebug(wxT("LB_SETITEMDATA failed"));
420 bool wxListBox::HasMultipleSelection() const
422 return (m_windowStyle
& wxLB_MULTIPLE
) || (m_windowStyle
& wxLB_EXTENDED
);
425 // Return number of selections and an array of selected integers
426 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
430 if ( HasMultipleSelection() )
432 int no_sel
= ListBox_GetSelCount(GetHwnd());
434 int *selections
= new int[no_sel
];
435 int rc
= ListBox_GetSelItems(GetHwnd(), no_sel
, selections
);
437 wxCHECK_MSG(rc
!= LB_ERR
, -1, wxT("ListBox_GetSelItems failed"));
439 aSelections
.Alloc(no_sel
);
440 for ( int n
= 0; n
< no_sel
; n
++ )
441 aSelections
.Add(selections
[n
]);
443 delete [] selections
;
448 else // single-selection listbox
450 aSelections
.Add(ListBox_GetCurSel(GetHwnd()));
456 // Get single selection, for single choice list items
457 int wxListBox::GetSelection() const
459 wxCHECK_MSG( !HasMultipleSelection(),
461 wxT("GetSelection() can't be used with multiple-selection "
462 "listboxes, use GetSelections() instead.") );
464 return ListBox_GetCurSel(GetHwnd());
467 // Find string for position
468 wxString
wxListBox::GetString(int N
) const
470 wxCHECK_MSG( N
>= 0 && N
< m_noItems
, "",
471 wxT("invalid index in wxListBox::GetClientData") );
473 int len
= ListBox_GetTextLen(GetHwnd(), N
);
475 // +1 for terminating NUL
477 ListBox_GetText(GetHwnd(), N
, result
.GetWriteBuf(len
+ 1));
478 result
.UngetWriteBuf();
484 wxListBox::DoInsertItems(const wxArrayString
& items
, int pos
)
486 wxCHECK_RET( pos
>= 0 && pos
<= m_noItems
,
487 wxT("invalid index in wxListBox::InsertItems") );
489 int nItems
= items
.GetCount();
490 for ( int i
= 0; i
< nItems
; i
++ )
491 ListBox_InsertString(GetHwnd(), i
+ pos
, items
[i
]);
494 SetHorizontalExtent();
497 void wxListBox::SetString(int N
, const wxString
& s
)
499 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
500 wxT("invalid index in wxListBox::SetString") );
502 // remember the state of the item
503 bool wasSelected
= IsSelected(N
);
505 void *oldData
= NULL
;
506 wxClientData
*oldObjData
= NULL
;
507 if ( m_clientDataItemsType
== ClientData_Void
)
508 oldData
= GetClientData(N
);
509 else if ( m_clientDataItemsType
== ClientData_Object
)
510 oldObjData
= GetClientObject(N
);
512 // delete and recreate it
513 SendMessage(GetHwnd(), LB_DELETESTRING
, N
, 0);
516 if ( N
== m_noItems
- 1 )
519 ListBox_InsertString(GetHwnd(), newN
, s
);
521 // restore the client data
523 SetClientData(N
, oldData
);
524 else if ( oldObjData
)
525 SetClientObject(N
, oldObjData
);
527 // we may have lost the selection
531 #if wxUSE_OWNER_DRAWN
532 if ( m_windowStyle
& wxLB_OWNERDRAW
)
533 // update item's text
534 m_aItems
[N
]->SetName(s
);
535 #endif //USE_OWNER_DRAWN
538 int wxListBox::GetCount() const
543 // ----------------------------------------------------------------------------
545 // ----------------------------------------------------------------------------
547 // Windows-specific code to set the horizontal extent of the listbox, if
548 // necessary. If s is non-NULL, it's used to calculate the horizontal extent.
549 // Otherwise, all strings are used.
550 void wxListBox::SetHorizontalExtent(const wxString
& s
)
552 // Only necessary if we want a horizontal scrollbar
553 if (!(m_windowStyle
& wxHSCROLL
))
555 TEXTMETRIC lpTextMetric
;
559 int existingExtent
= (int)SendMessage(GetHwnd(), LB_GETHORIZONTALEXTENT
, 0, 0L);
560 HDC dc
= GetWindowDC(GetHwnd());
562 if (GetFont().Ok() && GetFont().GetResourceHandle())
563 oldFont
= (HFONT
) ::SelectObject(dc
, (HFONT
) GetFont().GetResourceHandle());
565 GetTextMetrics(dc
, &lpTextMetric
);
567 ::GetTextExtentPoint(dc
, (LPTSTR
) (const wxChar
*)s
, s
.Length(), &extentXY
);
568 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
571 ::SelectObject(dc
, oldFont
);
573 ReleaseDC(GetHwnd(), dc
);
574 if (extentX
> existingExtent
)
575 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(extentX
), 0L);
579 int largestExtent
= 0;
580 HDC dc
= GetWindowDC(GetHwnd());
582 if (GetFont().Ok() && GetFont().GetResourceHandle())
583 oldFont
= (HFONT
) ::SelectObject(dc
, (HFONT
) GetFont().GetResourceHandle());
585 GetTextMetrics(dc
, &lpTextMetric
);
587 for (i
= 0; i
< m_noItems
; i
++)
589 int len
= (int)SendMessage(GetHwnd(), LB_GETTEXT
, i
, (LONG
)wxBuffer
);
592 ::GetTextExtentPoint(dc
, (LPTSTR
)wxBuffer
, len
, &extentXY
);
593 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
594 if (extentX
> largestExtent
)
595 largestExtent
= extentX
;
598 ::SelectObject(dc
, oldFont
);
600 ReleaseDC(GetHwnd(), dc
);
601 SendMessage(GetHwnd(), LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
605 wxSize
wxListBox::DoGetBestSize()
607 // find the widest string
610 for ( int i
= 0; i
< m_noItems
; i
++ )
612 wxString
str(GetString(i
));
613 GetTextExtent(str
, &wLine
, NULL
);
614 if ( wLine
> wListbox
)
618 // give it some reasonable default value if there are no strings in the
623 // the listbox should be slightly larger than the widest string
625 wxGetCharSize(GetHWND(), &cx
, &cy
, &GetFont());
629 int hListbox
= EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy
)*(wxMax(m_noItems
, 7));
631 return wxSize(wListbox
, hListbox
);
634 // ----------------------------------------------------------------------------
636 // ----------------------------------------------------------------------------
638 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
641 if (param == LBN_SELCANCEL)
643 event.extraLong = FALSE;
646 if (param
== LBN_SELCHANGE
)
648 wxCommandEvent
event(wxEVT_COMMAND_LISTBOX_SELECTED
, m_windowId
);
649 wxArrayInt aSelections
;
650 int count
= GetSelections(aSelections
);
653 event
.m_commandInt
= aSelections
[0];
654 event
.m_clientData
= GetClientData(event
.m_commandInt
);
655 wxString
str(GetString(event
.m_commandInt
));
658 event
.m_commandString
= str
;
663 event
.m_commandInt
= -1;
664 event
.m_commandString
.Empty();
667 event
.SetEventObject( this );
668 ProcessCommand(event
);
671 else if (param
== LBN_DBLCLK
)
673 wxCommandEvent
event(wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
, m_windowId
);
674 event
.SetEventObject( this );
675 GetEventHandler()->ProcessEvent(event
);
682 WXHBRUSH
wxListBox::OnCtlColor(WXHDC pDC
, WXHWND pWnd
, WXUINT nCtlColor
,
683 WXUINT message
, WXWPARAM wParam
, WXLPARAM lParam
)
688 HBRUSH hbrush
= Ctl3dCtlColorEx(message
, wParam
, lParam
);
689 return (WXHBRUSH
) hbrush
;
693 if (GetParent()->GetTransparentBackground())
694 SetBkMode((HDC
) pDC
, TRANSPARENT
);
696 SetBkMode((HDC
) pDC
, OPAQUE
);
698 ::SetBkColor((HDC
) pDC
, RGB(GetBackgroundColour().Red(), GetBackgroundColour().Green(), GetBackgroundColour().Blue()));
699 ::SetTextColor((HDC
) pDC
, RGB(GetForegroundColour().Red(), GetForegroundColour().Green(), GetForegroundColour().Blue()));
701 wxBrush
*backgroundBrush
= wxTheBrushList
->FindOrCreateBrush(GetBackgroundColour(), wxSOLID
);
703 // Note that this will be cleaned up in wxApp::OnIdle, if backgroundBrush
704 // has a zero usage count.
705 backgroundBrush
->RealizeResource();
706 return (WXHBRUSH
) backgroundBrush
->GetResourceHandle();
709 // ----------------------------------------------------------------------------
710 // wxCheckListBox support
711 // ----------------------------------------------------------------------------
713 #if wxUSE_OWNER_DRAWN
718 // space beneath/above each row in pixels
719 // "standard" checklistbox use 1 here, some might prefer 2. 0 is ugly.
720 #define OWNER_DRAWN_LISTBOX_EXTRA_SPACE (1)
722 // the height is the same for all items
723 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
725 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
726 // message is not yet sent when we get here!
727 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
729 // only owner-drawn control should receive this message
730 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), FALSE
);
732 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
735 dc
.SetHDC((WXHDC
)CreateIC(wxT("DISPLAY"), NULL
, NULL
, 0));
736 dc
.SetFont(wxSystemSettings::GetSystemFont(wxSYS_ANSI_VAR_FONT
));
738 pStruct
->itemHeight
= dc
.GetCharHeight() + 2*OWNER_DRAWN_LISTBOX_EXTRA_SPACE
;
739 pStruct
->itemWidth
= dc
.GetCharWidth();
744 // forward the message to the appropriate item
745 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
747 // only owner-drawn control should receive this message
748 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), FALSE
);
750 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
752 long data
= ListBox_GetItemData(GetHwnd(), pStruct
->itemID
);
754 wxCHECK( data
&& (data
!= LB_ERR
), FALSE
);
756 wxListBoxItem
*pItem
= (wxListBoxItem
*)data
;
759 dc
.SetHDC((WXHDC
)pStruct
->hDC
, FALSE
);
760 wxRect
rect(wxPoint(pStruct
->rcItem
.left
, pStruct
->rcItem
.top
),
761 wxPoint(pStruct
->rcItem
.right
, pStruct
->rcItem
.bottom
));
763 return pItem
->OnDrawItem(dc
, rect
,
764 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
765 (wxOwnerDrawn::wxODStatus
)pStruct
->itemState
);