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"
24 #include "wx/listbox.h"
25 #include "wx/settings.h"
31 #include "wx/msw/private.h"
38 #include <wx/msw/gnuwin32/extra.h>
47 #include "wx/ownerdrw.h"
50 #include "wx/dynarray.h"
53 #if !USE_SHARED_LIBRARY
54 IMPLEMENT_DYNAMIC_CLASS(wxListBox
, wxControl
)
57 // ============================================================================
58 // list box item declaration and implementation
59 // ============================================================================
63 class wxListBoxItem
: public wxOwnerDrawn
66 wxListBoxItem(const wxString
& str
= "");
69 wxListBoxItem::wxListBoxItem(const wxString
& str
) : wxOwnerDrawn(str
, FALSE
)
71 // no bitmaps/checkmarks
75 wxOwnerDrawn
*wxListBox::CreateItem(size_t n
)
77 return new wxListBoxItem();
80 #endif //USE_OWNER_DRAWN
82 // ============================================================================
83 // list box control implementation
84 // ============================================================================
86 // this macro is dangerous but still better than tons of (HWND)GetHWND()
87 #define hwnd (HWND)GetHWND()
89 bool wxListBox::MSWCommand(WXUINT param
, WXWORD
WXUNUSED(id
))
92 if (param == LBN_SELCANCEL)
94 event.extraLong = FALSE;
97 if (param
== LBN_SELCHANGE
)
99 wxCommandEvent
event(wxEVT_COMMAND_LISTBOX_SELECTED
, m_windowId
);
100 wxArrayInt aSelections
;
101 int count
= GetSelections(aSelections
);
104 event
.m_commandInt
= aSelections
[0] ;
105 event
.m_clientData
= GetClientData(event
.m_commandInt
);
106 wxString
str(GetString(event
.m_commandInt
));
108 event
.m_commandString
= copystring((char *)(const char *)str
);
112 event
.m_commandInt
= -1 ;
113 event
.m_commandString
= copystring("") ;
116 event
.SetEventObject( this );
117 ProcessCommand(event
);
118 if (event
.m_commandString
)
119 delete[] event
.m_commandString
;
122 else if (param
== LBN_DBLCLK
)
124 wxCommandEvent
event(wxEVT_COMMAND_LISTBOX_DOUBLECLICKED
, m_windowId
);
125 event
.SetEventObject( this );
126 GetEventHandler()->ProcessEvent(event
) ;
134 wxListBox::wxListBox()
140 bool wxListBox::Create(wxWindow
*parent
,
144 int n
, const wxString choices
[],
146 const wxValidator
& validator
,
147 const wxString
& name
)
154 SetValidator(validator
);
157 parent
->AddChild(this);
159 wxSystemSettings settings
;
160 SetBackgroundColour(settings
.GetSystemColour(wxSYS_COLOUR_WINDOW
));
161 SetForegroundColour(parent
->GetForegroundColour());
163 m_windowId
= ( id
== -1 ) ? (int)NewControlId() : id
;
169 m_windowStyle
= style
;
171 DWORD wstyle
= WS_VSCROLL
| WS_TABSTOP
| LBS_NOTIFY
| LBS_HASSTRINGS
;
172 if (m_windowStyle
& wxLB_MULTIPLE
)
173 wstyle
|= LBS_MULTIPLESEL
;
174 else if (m_windowStyle
& wxLB_EXTENDED
)
175 wstyle
|= LBS_EXTENDEDSEL
;
177 if (m_windowStyle
& wxLB_ALWAYS_SB
)
178 wstyle
|= LBS_DISABLENOSCROLL
;
179 if (m_windowStyle
& wxLB_HSCROLL
)
180 wstyle
|= WS_HSCROLL
;
181 if (m_windowStyle
& wxLB_SORT
)
184 #if wxUSE_OWNER_DRAWN
185 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
186 // we don't support LBS_OWNERDRAWVARIABLE yet
187 wstyle
|= LBS_OWNERDRAWFIXED
;
191 // Without this style, you get unexpected heights, so e.g. constraint layout
192 // doesn't work properly
193 wstyle
|= LBS_NOINTEGRALHEIGHT
;
196 WXDWORD exStyle
= Determine3DEffects(WS_EX_CLIENTEDGE
, &want3D
) ;
198 // Even with extended styles, need to combine with WS_BORDER
199 // for them to look right.
200 if ( want3D
|| wxStyleHasBorder(m_windowStyle
) )
205 m_hWnd
= (WXHWND
)::CreateWindowEx(exStyle
, "LISTBOX", NULL
,
208 (HWND
)parent
->GetHWND(), (HMENU
)m_windowId
,
209 wxGetInstance(), NULL
);
211 wxCHECK_MSG( m_hWnd
, FALSE
, "Failed to create listbox" );
216 Ctl3dSubclassCtl(hwnd
);
221 // Subclass again to catch messages
225 for (ui
= 0; ui
< (size_t)n
; ui
++) {
229 if ( (m_windowStyle
& wxLB_MULTIPLE
) == 0 )
230 SendMessage(hwnd
, LB_SETCURSEL
, 0, 0);
232 SetFont(parent
->GetFont());
234 SetSize(x
, y
, width
, height
);
241 wxListBox::~wxListBox()
243 #if wxUSE_OWNER_DRAWN
244 size_t uiCount
= m_aItems
.Count();
245 while ( uiCount
-- != 0 ) {
246 delete m_aItems
[uiCount
];
248 #endif // wxUSE_OWNER_DRAWN
251 void wxListBox::SetupColours()
253 SetBackgroundColour(wxSystemSettings::GetSystemColour(wxSYS_COLOUR_WINDOW
));
254 SetForegroundColour(GetParent()->GetForegroundColour());
257 void wxListBox::SetFirstItem(int N
)
259 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
260 "invalid index in wxListBox::SetFirstItem" );
262 SendMessage(hwnd
,LB_SETTOPINDEX
,(WPARAM
)N
,(LPARAM
)0) ;
265 void wxListBox::SetFirstItem(const wxString
& s
)
267 int N
= FindString(s
) ;
273 void wxListBox::Delete(int N
)
275 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
276 "invalid index in wxListBox::Delete" );
278 SendMessage(hwnd
, LB_DELETESTRING
, N
, 0);
281 SetHorizontalExtent("");
284 void wxListBox::Append(const wxString
& item
)
286 int index
= ListBox_AddString(hwnd
, item
);
289 #if wxUSE_OWNER_DRAWN
290 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
291 wxOwnerDrawn
*pNewItem
= CreateItem(index
); // dummy argument
292 pNewItem
->SetName(item
);
293 m_aItems
.Add(pNewItem
);
294 ListBox_SetItemData(hwnd
, index
, pNewItem
);
298 SetHorizontalExtent(item
);
301 void wxListBox::Append(const wxString
& item
, char *Client_data
)
303 int index
= ListBox_AddString(hwnd
, item
);
306 #if wxUSE_OWNER_DRAWN
307 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
308 // client data must be pointer to wxOwnerDrawn, otherwise we would crash
309 // in OnMeasure/OnDraw.
310 wxFAIL_MSG("Can't use client data with owner-drawn listboxes");
315 ListBox_SetItemData(hwnd
, index
, Client_data
);
317 SetHorizontalExtent(item
);
320 void wxListBox::Set(int n
, const wxString
*choices
, char** clientData
)
322 ShowWindow(hwnd
, SW_HIDE
);
323 ListBox_ResetContent(hwnd
);
325 for (i
= 0; i
< n
; i
++)
327 ListBox_AddString(hwnd
, choices
[i
]);
329 ListBox_SetItemData(hwnd
, i
, clientData
[i
]);
333 #if wxUSE_OWNER_DRAWN
334 if ( m_windowStyle
& wxLB_OWNERDRAW
) {
335 // first delete old items
336 size_t ui
= m_aItems
.Count();
337 while ( ui
-- != 0 ) {
342 // then create new ones
343 for (ui
= 0; ui
< (size_t)n
; ui
++) {
344 wxOwnerDrawn
*pNewItem
= CreateItem(ui
);
345 pNewItem
->SetName(choices
[ui
]);
346 m_aItems
.Add(pNewItem
);
347 ListBox_SetItemData(hwnd
, ui
, pNewItem
);
349 wxASSERT_MSG(clientData
[ui
] == NULL
,
350 "Can't use client data with owner-drawn listboxes");
355 SetHorizontalExtent("");
356 ShowWindow(hwnd
, SW_SHOW
);
359 int wxListBox::FindString(const wxString
& s
) const
361 int pos
= ListBox_FindStringExact(hwnd
, (WPARAM
)-1, s
);
368 void wxListBox::Clear()
370 ListBox_ResetContent(hwnd
);
372 #if wxUSE_OWNER_DRAWN
373 size_t uiCount
= m_aItems
.Count();
374 while ( uiCount
-- != 0 ) {
375 delete m_aItems
[uiCount
];
379 #endif // wxUSE_OWNER_DRAWN
382 ListBox_GetHorizontalExtent(hwnd
);
385 void wxListBox::SetSelection(int N
, bool select
)
387 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
388 "invalid index in wxListBox::SetSelection" );
390 if ((m_windowStyle
& wxLB_MULTIPLE
) || (m_windowStyle
& wxLB_EXTENDED
))
391 SendMessage(hwnd
, LB_SETSEL
, select
, N
);
397 SendMessage(hwnd
, LB_SETCURSEL
, N1
, 0);
401 bool wxListBox::Selected(int N
) const
403 wxCHECK_MSG( N
>= 0 && N
< m_noItems
, FALSE
,
404 "invalid index in wxListBox::Selected" );
406 return SendMessage(hwnd
, LB_GETSEL
, N
, 0) == 0 ? FALSE
: TRUE
;
409 void wxListBox::Deselect(int N
)
411 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
412 "invalid index in wxListBox::Deselect" );
414 if ((m_windowStyle
& wxLB_MULTIPLE
) || (m_windowStyle
& wxLB_EXTENDED
))
415 SendMessage(hwnd
, LB_SETSEL
, FALSE
, N
);
418 char *wxListBox::GetClientData(int N
) const
420 wxCHECK_MSG( N
>= 0 && N
< m_noItems
, NULL
,
421 "invalid index in wxListBox::GetClientData" );
423 return (char *)SendMessage(hwnd
, LB_GETITEMDATA
, N
, 0);
426 void wxListBox::SetClientData(int N
, char *Client_data
)
428 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
429 "invalid index in wxListBox::SetClientData" );
431 if ( ListBox_SetItemData(hwnd
, N
, Client_data
) == LB_ERR
)
432 wxLogDebug("LB_SETITEMDATA failed");
435 // Return number of selections and an array of selected integers
436 int wxListBox::GetSelections(wxArrayInt
& aSelections
) const
440 if ((m_windowStyle
& wxLB_MULTIPLE
) || (m_windowStyle
& wxLB_EXTENDED
))
442 int no_sel
= ListBox_GetSelCount(hwnd
);
444 int *selections
= new int[no_sel
];
445 if ( ListBox_GetSelItems(hwnd
, no_sel
, selections
) == LB_ERR
) {
446 wxFAIL_MSG("This listbox can't have single-selection style!");
449 aSelections
.Alloc(no_sel
);
450 for ( int n
= 0; n
< no_sel
; n
++ )
451 aSelections
.Add(selections
[n
]);
453 delete [] selections
;
458 else // single-selection listbox
460 aSelections
.Add(ListBox_GetCurSel(hwnd
));
466 // Get single selection, for single choice list items
467 int wxListBox::GetSelection() const
469 wxCHECK_MSG( !(m_windowStyle
& wxLB_MULTIPLE
) &&
470 !(m_windowStyle
& wxLB_EXTENDED
),
472 "GetSelection() can't be used with multiple-selection "
473 "listboxes, use GetSelections() instead." );
475 return ListBox_GetCurSel(hwnd
);
478 // Find string for position
479 wxString
wxListBox::GetString(int N
) const
481 wxCHECK_MSG( N
>= 0 && N
< m_noItems
, "",
482 "invalid index in wxListBox::GetClientData" );
484 int len
= ListBox_GetTextLen(hwnd
, N
);
486 // +1 for terminating NUL
488 ListBox_GetText(hwnd
, N
, result
.GetWriteBuf(len
+ 1));
489 result
.UngetWriteBuf();
494 void wxListBox::DoSetSize(int x
, int y
, int width
, int height
, int sizeFlags
)
496 int currentX
, currentY
;
497 GetPosition(¤tX
, ¤tY
);
504 if (x
== -1 || (sizeFlags
& wxSIZE_ALLOW_MINUS_ONE
))
506 if (y
== -1 || (sizeFlags
& wxSIZE_ALLOW_MINUS_ONE
))
509 AdjustForParentClientOrigin(x1
, y1
, sizeFlags
);
511 // If we're prepared to use the existing size, then...
512 if (width
== -1 && height
== -1 && ((sizeFlags
& wxSIZE_AUTO
) != wxSIZE_AUTO
))
517 int cx
; // button font dimensions
520 wxGetCharSize(GetHWND(), &cx
, &cy
, & this->GetFont());
522 float control_width
, control_height
, control_x
, control_y
;
524 // Deal with default size (using -1 values)
526 w1
= DEFAULT_ITEM_WIDTH
;
529 h1
= DEFAULT_ITEM_HEIGHT
;
531 control_x
= (float)x1
;
532 control_y
= (float)y1
;
533 control_width
= (float)w1
;
534 control_height
= (float)h1
;
536 // Calculations may have made size too small
537 if (control_height
<= 0)
538 control_height
= (float)DEFAULT_ITEM_HEIGHT
;
540 if (control_width
<= 0)
541 control_width
= (float)DEFAULT_ITEM_WIDTH
;
544 (int)control_x
, (int)control_y
,
545 (int)control_width
, (int)control_height
,
550 // Windows-specific code to set the horizontal extent of
551 // the listbox, if necessary. If s is non-NULL, it's
552 // used to calculate the horizontal extent.
553 // Otherwise, all strings are used.
554 void wxListBox::SetHorizontalExtent(const wxString
& s
)
556 // Only necessary if we want a horizontal scrollbar
557 if (!(m_windowStyle
& wxHSCROLL
))
559 TEXTMETRIC lpTextMetric
;
563 int existingExtent
= (int)SendMessage(hwnd
, LB_GETHORIZONTALEXTENT
, 0, 0L);
564 HDC dc
= GetWindowDC(hwnd
);
566 if (GetFont().Ok() && GetFont().GetResourceHandle())
567 oldFont
= (HFONT
) ::SelectObject(dc
, (HFONT
) GetFont().GetResourceHandle());
569 GetTextMetrics(dc
, &lpTextMetric
);
571 ::GetTextExtentPoint(dc
, (LPSTR
) (const char *)s
, s
.Length(), &extentXY
);
572 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
575 ::SelectObject(dc
, oldFont
);
578 if (extentX
> existingExtent
)
579 SendMessage(hwnd
, LB_SETHORIZONTALEXTENT
, LOWORD(extentX
), 0L);
584 int largestExtent
= 0;
585 HDC dc
= GetWindowDC(hwnd
);
587 if (GetFont().Ok() && GetFont().GetResourceHandle())
588 oldFont
= (HFONT
) ::SelectObject(dc
, (HFONT
) GetFont().GetResourceHandle());
590 GetTextMetrics(dc
, &lpTextMetric
);
592 for (i
= 0; i
< m_noItems
; i
++)
594 int len
= (int)SendMessage(hwnd
, LB_GETTEXT
, i
, (LONG
)wxBuffer
);
597 ::GetTextExtentPoint(dc
, (LPSTR
)wxBuffer
, len
, &extentXY
);
598 int extentX
= (int)(extentXY
.cx
+ lpTextMetric
.tmAveCharWidth
);
599 if (extentX
> largestExtent
)
600 largestExtent
= extentX
;
603 ::SelectObject(dc
, oldFont
);
606 SendMessage(hwnd
, LB_SETHORIZONTALEXTENT
, LOWORD(largestExtent
), 0L);
611 wxListBox::InsertItems(int nItems
, const wxString items
[], int pos
)
613 wxCHECK_RET( pos
>= 0 && pos
<= m_noItems
,
614 "invalid index in wxListBox::InsertItems" );
617 for (i
= 0; i
< nItems
; i
++)
618 ListBox_InsertString(hwnd
, i
+ pos
, items
[i
]);
621 SetHorizontalExtent("");
624 void wxListBox::SetString(int N
, const wxString
& s
)
626 wxCHECK_RET( N
>= 0 && N
< m_noItems
,
627 "invalid index in wxListBox::SetString" );
630 if (!(m_windowStyle
& wxLB_MULTIPLE
) && !(m_windowStyle
& wxLB_EXTENDED
))
631 sel
= GetSelection();
633 char *oldData
= (char *)wxListBox::GetClientData(N
);
635 SendMessage(hwnd
, LB_DELETESTRING
, N
, 0);
638 if (N
== (m_noItems
- 1))
641 SendMessage(hwnd
, LB_INSERTSTRING
, newN
, (LPARAM
) (const char *)s
);
643 wxListBox::SetClientData(N
, oldData
);
645 // Selection may have changed
649 #if wxUSE_OWNER_DRAWN
650 if ( m_windowStyle
& wxLB_OWNERDRAW
)
651 // update item's text
652 m_aItems
[N
]->SetName(s
);
653 #endif //USE_OWNER_DRAWN
656 int wxListBox::Number () const
661 // For single selection items only
662 wxString
wxListBox::GetStringSelection () const
664 int sel
= GetSelection ();
666 return this->GetString (sel
);
671 bool wxListBox::SetStringSelection (const wxString
& s
, bool flag
)
673 int sel
= FindString (s
);
676 SetSelection (sel
, flag
);
683 // Is this the right thing? Won't setselection generate a command
684 // event too? No! It'll just generate a setselection event.
685 // But we still can't have this being called whenever a real command
686 // is generated, because it sets the selection, which will already
687 // have been done! (Unless we have an optional argument for calling
688 // by the actual window system, or a separate function, ProcessCommand)
689 void wxListBox::Command (wxCommandEvent
& event
)
691 if (event
.m_extraLong
)
692 SetSelection (event
.m_commandInt
);
695 Deselect (event
.m_commandInt
);
698 ProcessCommand (event
);
701 WXHBRUSH
wxListBox::OnCtlColor(WXHDC pDC
, WXHWND pWnd
, WXUINT nCtlColor
,
702 WXUINT message
, WXWPARAM wParam
, WXLPARAM lParam
)
707 HBRUSH hbrush
= Ctl3dCtlColorEx(message
, wParam
, lParam
);
708 return (WXHBRUSH
) hbrush
;
712 if (GetParent()->GetTransparentBackground())
713 SetBkMode((HDC
) pDC
, TRANSPARENT
);
715 SetBkMode((HDC
) pDC
, OPAQUE
);
717 ::SetBkColor((HDC
) pDC
, RGB(GetBackgroundColour().Red(), GetBackgroundColour().Green(), GetBackgroundColour().Blue()));
718 ::SetTextColor((HDC
) pDC
, RGB(GetForegroundColour().Red(), GetForegroundColour().Green(), GetForegroundColour().Blue()));
720 wxBrush
*backgroundBrush
= wxTheBrushList
->FindOrCreateBrush(GetBackgroundColour(), wxSOLID
);
722 // Note that this will be cleaned up in wxApp::OnIdle, if backgroundBrush
723 // has a zero usage count.
724 backgroundBrush
->RealizeResource();
725 return (WXHBRUSH
) backgroundBrush
->GetResourceHandle();
728 long wxListBox::MSWWindowProc(WXUINT nMsg
, WXWPARAM wParam
, WXLPARAM lParam
)
730 return wxControl::MSWWindowProc(nMsg
, wParam
, lParam
);
733 #if wxUSE_OWNER_DRAWN
738 // space beneath/above each row in pixels
739 // "standard" checklistbox use 1 here, some might prefer 2. 0 is ugly.
740 #define OWNER_DRAWN_LISTBOX_EXTRA_SPACE (1)
742 // the height is the same for all items
743 // TODO should be changed for LBS_OWNERDRAWVARIABLE style listboxes
745 // NB: can't forward this to wxListBoxItem because LB_SETITEMDATA
746 // message is not yet sent when we get here!
747 bool wxListBox::MSWOnMeasure(WXMEASUREITEMSTRUCT
*item
)
749 // only owner-drawn control should receive this message
750 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), FALSE
);
752 MEASUREITEMSTRUCT
*pStruct
= (MEASUREITEMSTRUCT
*)item
;
755 dc
.SetHDC((WXHDC
)CreateIC("DISPLAY", NULL
, NULL
, 0));
756 dc
.SetFont(wxSystemSettings::GetSystemFont(wxSYS_ANSI_VAR_FONT
));
758 pStruct
->itemHeight
= dc
.GetCharHeight() + 2*OWNER_DRAWN_LISTBOX_EXTRA_SPACE
;
759 pStruct
->itemWidth
= dc
.GetCharWidth();
764 // forward the message to the appropriate item
765 bool wxListBox::MSWOnDraw(WXDRAWITEMSTRUCT
*item
)
767 // only owner-drawn control should receive this message
768 wxCHECK( ((m_windowStyle
& wxLB_OWNERDRAW
) == wxLB_OWNERDRAW
), FALSE
);
770 DRAWITEMSTRUCT
*pStruct
= (DRAWITEMSTRUCT
*)item
;
772 long data
= ListBox_GetItemData(hwnd
, pStruct
->itemID
);
774 wxCHECK( data
&& (data
!= LB_ERR
), FALSE
);
776 wxListBoxItem
*pItem
= (wxListBoxItem
*)data
;
779 dc
.SetHDC((WXHDC
)pStruct
->hDC
, FALSE
);
780 wxRect
rect(wxPoint(pStruct
->rcItem
.left
, pStruct
->rcItem
.top
),
781 wxPoint(pStruct
->rcItem
.right
, pStruct
->rcItem
.bottom
));
783 return pItem
->OnDrawItem(dc
, rect
,
784 (wxOwnerDrawn::wxODAction
)pStruct
->itemAction
,
785 (wxOwnerDrawn::wxODStatus
)pStruct
->itemState
);