1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/menu.cpp
3 // Purpose: wxMenu, wxMenuBar, wxMenuItem
4 // Author: Julian Smart
5 // Modified by: Vadim Zeitlin
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ===========================================================================
14 // ===========================================================================
16 // ---------------------------------------------------------------------------
18 // ---------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
40 #include "wx/ownerdrw.h"
43 #include "wx/scopedarray.h"
45 #include "wx/msw/private.h"
46 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
54 #if (_WIN32_WCE < 400) && !defined(__HANDHELDPC__)
58 #include "wx/msw/wince/missing.h"
62 // other standard headers
66 #include "wx/dynlib.h"
69 #ifndef MNS_CHECKORBMP
70 #define MNS_CHECKORBMP 0x04000000
73 #define MIM_STYLE 0x00000010
76 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
80 // ----------------------------------------------------------------------------
82 // ----------------------------------------------------------------------------
84 // the (popup) menu title has this special id
85 static const UINT idMenuTitle
= (UINT
)-3;
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
94 // make the given menu item default
95 void SetDefaultMenuItem(HMENU
WXUNUSED_IN_WINCE(hmenu
),
96 UINT
WXUNUSED_IN_WINCE(id
))
101 mii
.cbSize
= sizeof(MENUITEMINFO
);
102 mii
.fMask
= MIIM_STATE
;
103 mii
.fState
= MFS_DEFAULT
;
105 if ( !::SetMenuItemInfo(hmenu
, id
, FALSE
, &mii
) )
107 wxLogLastError(wxT("SetMenuItemInfo"));
109 #endif // !__WXWINCE__
112 // make the given menu item owner-drawn
113 void SetOwnerDrawnMenuItem(HMENU
WXUNUSED_IN_WINCE(hmenu
),
114 UINT
WXUNUSED_IN_WINCE(id
),
115 ULONG_PTR
WXUNUSED_IN_WINCE(data
),
116 BOOL
WXUNUSED_IN_WINCE(byPositon
= FALSE
))
121 mii
.cbSize
= sizeof(MENUITEMINFO
);
122 mii
.fMask
= MIIM_FTYPE
| MIIM_DATA
;
123 mii
.fType
= MFT_OWNERDRAW
;
124 mii
.dwItemData
= data
;
126 if ( reinterpret_cast<wxMenuItem
*>(data
)->IsSeparator() )
127 mii
.fType
|= MFT_SEPARATOR
;
129 if ( !::SetMenuItemInfo(hmenu
, id
, byPositon
, &mii
) )
131 wxLogLastError(wxT("SetMenuItemInfo"));
133 #endif // !__WXWINCE__
137 UINT
GetMenuState(HMENU hMenu
, UINT id
, UINT flags
)
141 info
.cbSize
= sizeof(info
);
142 info
.fMask
= MIIM_STATE
;
143 // MF_BYCOMMAND is zero so test MF_BYPOSITION
144 if ( !::GetMenuItemInfo(hMenu
, id
, flags
& MF_BYPOSITION
? TRUE
: FALSE
, & info
) )
146 wxLogLastError(wxT("GetMenuItemInfo"));
150 #endif // __WXWINCE__
152 inline bool IsGreaterThanStdSize(const wxBitmap
& bmp
)
154 return bmp
.GetWidth() > ::GetSystemMetrics(SM_CXMENUCHECK
) ||
155 bmp
.GetHeight() > ::GetSystemMetrics(SM_CYMENUCHECK
);
158 } // anonymous namespace
160 // ============================================================================
162 // ============================================================================
164 #include "wx/listimpl.cpp"
166 WX_DEFINE_LIST( wxMenuInfoList
)
168 #if wxUSE_EXTENDED_RTTI
170 WX_DEFINE_FLAGS( wxMenuStyle
)
172 wxBEGIN_FLAGS( wxMenuStyle
)
173 wxFLAGS_MEMBER(wxMENU_TEAROFF
)
174 wxEND_FLAGS( wxMenuStyle
)
176 IMPLEMENT_DYNAMIC_CLASS_XTI(wxMenu
, wxEvtHandler
,"wx/menu.h")
178 wxCOLLECTION_TYPE_INFO( wxMenuItem
* , wxMenuItemList
) ;
180 template<> void wxCollectionToVariantArray( wxMenuItemList
const &theList
, wxxVariantArray
&value
)
182 wxListCollectionToVariantArray
<wxMenuItemList::compatibility_iterator
>( theList
, value
) ;
185 wxBEGIN_PROPERTIES_TABLE(wxMenu
)
186 wxEVENT_PROPERTY( Select
, wxEVT_COMMAND_MENU_SELECTED
, wxCommandEvent
)
187 wxPROPERTY( Title
, wxString
, SetTitle
, GetTitle
, wxString(), 0 /*flags*/ , wxT("Helpstring") , wxT("group") )
188 wxREADONLY_PROPERTY_FLAGS( MenuStyle
, wxMenuStyle
, long , GetStyle
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group")) // style
189 wxPROPERTY_COLLECTION( MenuItems
, wxMenuItemList
, wxMenuItem
* , Append
, GetMenuItems
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
190 wxEND_PROPERTIES_TABLE()
192 wxBEGIN_HANDLERS_TABLE(wxMenu
)
193 wxEND_HANDLERS_TABLE()
195 wxDIRECT_CONSTRUCTOR_2( wxMenu
, wxString
, Title
, long , MenuStyle
)
197 WX_DEFINE_FLAGS( wxMenuBarStyle
)
199 wxBEGIN_FLAGS( wxMenuBarStyle
)
200 wxFLAGS_MEMBER(wxMB_DOCKABLE
)
201 wxEND_FLAGS( wxMenuBarStyle
)
203 // the negative id would lead the window (its superclass !) to vetoe streaming out otherwise
204 bool wxMenuBarStreamingCallback( const wxObject
*WXUNUSED(object
), wxWriter
* , wxPersister
* , wxxVariantArray
& )
209 IMPLEMENT_DYNAMIC_CLASS_XTI_CALLBACK(wxMenuBar
, wxWindow
,"wx/menu.h",wxMenuBarStreamingCallback
)
211 IMPLEMENT_DYNAMIC_CLASS_XTI(wxMenuInfo
, wxObject
, "wx/menu.h" )
213 wxBEGIN_PROPERTIES_TABLE(wxMenuInfo
)
214 wxREADONLY_PROPERTY( Menu
, wxMenu
* , GetMenu
, EMPTY_MACROVALUE
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
215 wxREADONLY_PROPERTY( Title
, wxString
, GetTitle
, wxString() , 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
216 wxEND_PROPERTIES_TABLE()
218 wxBEGIN_HANDLERS_TABLE(wxMenuInfo
)
219 wxEND_HANDLERS_TABLE()
221 wxCONSTRUCTOR_2( wxMenuInfo
, wxMenu
* , Menu
, wxString
, Title
)
223 wxCOLLECTION_TYPE_INFO( wxMenuInfo
* , wxMenuInfoList
) ;
225 template<> void wxCollectionToVariantArray( wxMenuInfoList
const &theList
, wxxVariantArray
&value
)
227 wxListCollectionToVariantArray
<wxMenuInfoList::compatibility_iterator
>( theList
, value
) ;
230 wxBEGIN_PROPERTIES_TABLE(wxMenuBar
)
231 wxPROPERTY_COLLECTION( MenuInfos
, wxMenuInfoList
, wxMenuInfo
* , Append
, GetMenuInfos
, 0 /*flags*/ , wxT("Helpstring") , wxT("group"))
232 wxEND_PROPERTIES_TABLE()
234 wxBEGIN_HANDLERS_TABLE(wxMenuBar
)
235 wxEND_HANDLERS_TABLE()
237 wxCONSTRUCTOR_DUMMY( wxMenuBar
)
240 IMPLEMENT_DYNAMIC_CLASS(wxMenu
, wxEvtHandler
)
241 IMPLEMENT_DYNAMIC_CLASS(wxMenuBar
, wxWindow
)
242 IMPLEMENT_DYNAMIC_CLASS(wxMenuInfo
, wxObject
)
245 const wxMenuInfoList
& wxMenuBar::GetMenuInfos() const
247 wxMenuInfoList
* list
= const_cast< wxMenuInfoList
* >( &m_menuInfos
) ;
248 WX_CLEAR_LIST( wxMenuInfoList
, *list
) ;
249 for( size_t i
= 0 ; i
< GetMenuCount() ; ++i
)
251 wxMenuInfo
* info
= new wxMenuInfo() ;
252 info
->Create( const_cast<wxMenuBar
*>(this)->GetMenu(i
) , GetMenuLabel(i
) ) ;
253 list
->Append( info
) ;
258 // ---------------------------------------------------------------------------
259 // wxMenu construction, adding and removing menu items
260 // ---------------------------------------------------------------------------
262 // Construct a menu with optional title (then use append)
266 m_startRadioGroup
= -1;
268 #if wxUSE_OWNER_DRAWN
269 m_ownerDrawn
= false;
270 m_maxBitmapWidth
= 0;
271 m_maxAccelWidth
= -1;
272 #endif // wxUSE_OWNER_DRAWN
275 m_hMenu
= (WXHMENU
)CreatePopupMenu();
278 wxLogLastError(wxT("CreatePopupMenu"));
281 // if we have a title, insert it in the beginning of the menu
282 if ( !m_title
.empty() )
284 Append(idMenuTitle
, m_title
);
289 // The wxWindow destructor will take care of deleting the submenus.
292 // we should free Windows resources only if Windows doesn't do it for us
293 // which happens if we're attached to a menubar or a submenu of another
295 if ( !IsAttached() && !GetParent() )
297 if ( !::DestroyMenu(GetHmenu()) )
299 wxLogLastError(wxT("DestroyMenu"));
305 WX_CLEAR_ARRAY(m_accels
);
306 #endif // wxUSE_ACCEL
311 // this will take effect during the next call to Append()
315 void wxMenu::Attach(wxMenuBarBase
*menubar
)
317 wxMenuBase::Attach(menubar
);
324 int wxMenu::FindAccel(int id
) const
326 size_t n
, count
= m_accels
.GetCount();
327 for ( n
= 0; n
< count
; n
++ )
329 if ( m_accels
[n
]->m_command
== id
)
336 void wxMenu::UpdateAccel(wxMenuItem
*item
)
338 if ( item
->IsSubMenu() )
340 wxMenu
*submenu
= item
->GetSubMenu();
341 wxMenuItemList::compatibility_iterator node
= submenu
->GetMenuItems().GetFirst();
344 UpdateAccel(node
->GetData());
346 node
= node
->GetNext();
349 else if ( !item
->IsSeparator() )
351 // recurse upwards: we should only modify m_accels of the top level
352 // menus, not of the submenus as wxMenuBar doesn't look at them
353 // (alternative and arguable cleaner solution would be to recurse
354 // downwards in GetAccelCount() and CopyAccels())
357 GetParent()->UpdateAccel(item
);
361 // find the (new) accel for this item
362 wxAcceleratorEntry
*accel
= wxAcceleratorEntry::Create(item
->GetItemLabel());
364 accel
->m_command
= item
->GetId();
367 int n
= FindAccel(item
->GetId());
368 if ( n
== wxNOT_FOUND
)
370 // no old, add new if any
374 return; // skipping RebuildAccelTable() below
378 // replace old with new or just remove the old one if no new
383 m_accels
.RemoveAt(n
);
388 GetMenuBar()->RebuildAccelTable();
391 ResetMaxAccelWidth();
393 //else: it is a separator, they can't have accels, nothing to do
396 #endif // wxUSE_ACCEL
401 // helper of DoInsertOrAppend(): returns the HBITMAP to use in MENUITEMINFO
402 HBITMAP
GetHBitmapForMenu(wxMenuItem
*pItem
, bool checked
= true)
404 // Under versions of Windows older than Vista we can't pass HBITMAP
405 // directly as hbmpItem for 2 reasons:
406 // 1. We can't draw it with transparency then (this is not
407 // very important now but would be with themed menu bg)
408 // 2. Worse, Windows inverts the bitmap for the selected
409 // item and this looks downright ugly
411 // So we prefer to instead draw it ourselves in MSWOnDrawItem().by using
412 // HBMMENU_CALLBACK when inserting it
414 // However under Vista using HBMMENU_CALLBACK causes the entire menu to be
415 // drawn using the classic theme instead of the current one and it does
416 // handle transparency just fine so do use the real bitmap there
418 if ( wxGetWinVersion() >= wxWinVersion_Vista
)
420 wxBitmap bmp
= pItem
->GetBitmap(checked
);
423 // we must use PARGB DIB for the menu bitmaps so ensure that we do
424 wxImage
img(bmp
.ConvertToImage());
425 if ( !img
.HasAlpha() )
428 pItem
->SetBitmap(img
, checked
);
431 return GetHbitmapOf(pItem
->GetBitmap(checked
));
433 //else: bitmap is not set
437 #endif // wxUSE_IMAGE
439 return HBMMENU_CALLBACK
;
442 } // anonymous namespace
444 // append a new item or submenu to the menu
445 bool wxMenu::DoInsertOrAppend(wxMenuItem
*pItem
, size_t pos
)
449 #endif // wxUSE_ACCEL
451 // we should support disabling the item even prior to adding it to the menu
452 UINT flags
= pItem
->IsEnabled() ? MF_ENABLED
: MF_GRAYED
;
454 // if "Break" has just been called, insert a menu break before this item
455 // (and don't forget to reset the flag)
457 flags
|= MF_MENUBREAK
;
461 if ( pItem
->IsSeparator() ) {
462 flags
|= MF_SEPARATOR
;
465 // id is the numeric id for normal menu items and HMENU for submenus as
466 // required by ::AppendMenu() API
468 wxMenu
*submenu
= pItem
->GetSubMenu();
469 if ( submenu
!= NULL
) {
470 wxASSERT_MSG( submenu
->GetHMenu(), wxT("invalid submenu") );
472 submenu
->SetParent(this);
474 id
= (UINT_PTR
)submenu
->GetHMenu();
479 id
= pItem
->GetMSWId();
483 // prepare to insert the item in the menu
484 wxString itemText
= pItem
->GetItemLabel();
485 LPCTSTR pData
= NULL
;
486 if ( pos
== (size_t)-1 )
488 // append at the end (note that the item is already appended to
489 // internal data structures)
490 pos
= GetMenuItemCount() - 1;
493 // adjust position to account for the title, if any
494 if ( !m_title
.empty() )
495 pos
+= 2; // for the title itself and its separator
499 #if wxUSE_OWNER_DRAWN
500 // Under older systems mixing owner-drawn and non-owner-drawn items results
501 // in inconsistent margins, so we force this one to be owner-drawn if any
502 // other items already are.
504 pItem
->SetOwnerDrawn(true);
505 #endif // wxUSE_OWNER_DRAWN
507 // check if we have something more than a simple text item
508 #if wxUSE_OWNER_DRAWN
509 if ( pItem
->IsOwnerDrawn() )
513 if ( !m_ownerDrawn
&& !pItem
->IsSeparator() )
515 // MIIM_BITMAP only works under WinME/2000+ so we always use owner
516 // drawn item under the previous versions and we also have to use
517 // them in any case if the item has custom colours or font
518 static const wxWinVersion winver
= wxGetWinVersion();
519 bool mustUseOwnerDrawn
= winver
< wxWinVersion_98
||
520 pItem
->GetTextColour().Ok() ||
521 pItem
->GetBackgroundColour().Ok() ||
522 pItem
->GetFont().Ok();
524 if ( !mustUseOwnerDrawn
)
526 const wxBitmap
& bmpUnchecked
= pItem
->GetBitmap(false),
527 bmpChecked
= pItem
->GetBitmap(true);
529 if ( (bmpUnchecked
.Ok() && IsGreaterThanStdSize(bmpUnchecked
)) ||
530 (bmpChecked
.Ok() && IsGreaterThanStdSize(bmpChecked
)) )
532 mustUseOwnerDrawn
= true;
536 // use InsertMenuItem() if possible as it's guaranteed to look
537 // correct while our owner-drawn code is not
538 if ( !mustUseOwnerDrawn
)
540 WinStruct
<MENUITEMINFO
> mii
;
541 mii
.fMask
= MIIM_STRING
| MIIM_DATA
;
543 // don't set hbmpItem for the checkable items as it would
544 // be used for both checked and unchecked state
545 if ( pItem
->IsCheckable() )
547 mii
.fMask
|= MIIM_CHECKMARKS
;
548 mii
.hbmpChecked
= GetHBitmapForMenu(pItem
, true);
549 mii
.hbmpUnchecked
= GetHBitmapForMenu(pItem
, false);
551 else if ( pItem
->GetBitmap().IsOk() )
553 mii
.fMask
|= MIIM_BITMAP
;
554 mii
.hbmpItem
= GetHBitmapForMenu(pItem
);
557 mii
.cch
= itemText
.length();
558 mii
.dwTypeData
= const_cast<wxChar
*>(itemText
.wx_str());
560 if ( flags
& MF_POPUP
)
562 mii
.fMask
|= MIIM_SUBMENU
;
563 mii
.hSubMenu
= GetHmenuOf(pItem
->GetSubMenu());
567 mii
.fMask
|= MIIM_ID
;
571 mii
.dwItemData
= reinterpret_cast<ULONG_PTR
>(pItem
);
573 ok
= ::InsertMenuItem(GetHmenu(), pos
, TRUE
/* by pos */, &mii
);
576 wxLogLastError(wxT("InsertMenuItem()"));
578 else // InsertMenuItem() ok
580 // we need to remove the extra indent which is reserved for
581 // the checkboxes by default as it looks ugly unless check
582 // boxes are used together with bitmaps and this is not the
584 WinStruct
<MENUINFO
> mi
;
586 // don't call SetMenuInfo() directly, this would prevent
587 // the app from starting up under Windows 95/NT 4
588 typedef BOOL (WINAPI
*SetMenuInfo_t
)(HMENU
, MENUINFO
*);
590 wxDynamicLibrary
dllUser(wxT("user32"));
591 wxDYNLIB_FUNCTION(SetMenuInfo_t
, SetMenuInfo
, dllUser
);
592 if ( pfnSetMenuInfo
)
594 mi
.fMask
= MIM_STYLE
;
595 mi
.dwStyle
= MNS_CHECKORBMP
;
596 if ( !(*pfnSetMenuInfo
)(GetHmenu(), &mi
) )
598 wxLogLastError(wxT("SetMenuInfo(MNS_NOCHECK)"));
602 // tell the item that it's not really owner-drawn but only
603 // needs to draw its bitmap, the rest is done by Windows
604 pItem
->SetOwnerDrawn(false);
612 // item draws itself, pass pointer to it in data parameter
613 flags
|= MF_OWNERDRAW
;
614 pData
= (LPCTSTR
)pItem
;
616 bool updateAllMargins
= false;
618 // get size of bitmap always return valid value (0 for invalid bitmap),
619 // so we don't needed check if bitmap is valid ;)
620 int uncheckedW
= pItem
->GetBitmap(false).GetWidth();
621 int checkedW
= pItem
->GetBitmap(true).GetWidth();
623 if ( m_maxBitmapWidth
< uncheckedW
)
625 m_maxBitmapWidth
= uncheckedW
;
626 updateAllMargins
= true;
629 if ( m_maxBitmapWidth
< checkedW
)
631 m_maxBitmapWidth
= checkedW
;
632 updateAllMargins
= true;
635 // make other item ownerdrawn and update margin width for equals alignment
636 if ( !m_ownerDrawn
|| updateAllMargins
)
638 // we must use position in SetOwnerDrawnMenuItem because
639 // all separators have the same id
641 wxMenuItemList::compatibility_iterator node
= GetMenuItems().GetFirst();
644 wxMenuItem
* item
= node
->GetData();
646 if ( !item
->IsOwnerDrawn())
648 item
->SetOwnerDrawn(true);
649 SetOwnerDrawnMenuItem(GetHmenu(), pos
,
650 reinterpret_cast<ULONG_PTR
>(item
), TRUE
);
653 item
->SetMarginWidth(m_maxBitmapWidth
);
655 node
= node
->GetNext();
659 // set menu as ownerdrawn
662 ResetMaxAccelWidth();
664 // only update our margin for equals alignment to other item
665 else if ( !updateAllMargins
)
667 pItem
->SetMarginWidth(m_maxBitmapWidth
);
672 #endif // wxUSE_OWNER_DRAWN
674 // item is just a normal string (passed in data parameter)
678 itemText
= wxMenuItem::GetLabelText(itemText
);
681 pData
= (wxChar
*)itemText
.wx_str();
684 // item might have already been inserted by InsertMenuItem() above
687 if ( !::InsertMenu(GetHmenu(), pos
, flags
| MF_BYPOSITION
, id
, pData
) )
689 wxLogLastError(wxT("InsertMenu[Item]()"));
696 // if we just appended the title, highlight it
697 if ( id
== idMenuTitle
)
699 // visually select the menu title
700 SetDefaultMenuItem(GetHmenu(), id
);
703 // if we're already attached to the menubar, we must update it
704 if ( IsAttached() && GetMenuBar()->IsAttached() )
706 GetMenuBar()->Refresh();
712 void wxMenu::EndRadioGroup()
714 // we're not inside a radio group any longer
715 m_startRadioGroup
= -1;
718 wxMenuItem
* wxMenu::DoAppend(wxMenuItem
*item
)
720 wxCHECK_MSG( item
, NULL
, wxT("NULL item in wxMenu::DoAppend") );
724 if ( item
->GetKind() == wxITEM_RADIO
)
726 int count
= GetMenuItemCount();
728 if ( m_startRadioGroup
== -1 )
730 // start a new radio group
731 m_startRadioGroup
= count
;
733 // for now it has just one element
734 item
->SetAsRadioGroupStart();
735 item
->SetRadioGroupEnd(m_startRadioGroup
);
737 // ensure that we have a checked item in the radio group
740 else // extend the current radio group
742 // we need to update its end item
743 item
->SetRadioGroupStart(m_startRadioGroup
);
744 wxMenuItemList::compatibility_iterator node
= GetMenuItems().Item(m_startRadioGroup
);
748 node
->GetData()->SetRadioGroupEnd(count
);
752 wxFAIL_MSG( wxT("where is the radio group start item?") );
756 else // not a radio item
761 if ( !wxMenuBase::DoAppend(item
) || !DoInsertOrAppend(item
) )
768 // check the item initially
775 wxMenuItem
* wxMenu::DoInsert(size_t pos
, wxMenuItem
*item
)
777 if (wxMenuBase::DoInsert(pos
, item
) && DoInsertOrAppend(item
, pos
))
783 wxMenuItem
*wxMenu::DoRemove(wxMenuItem
*item
)
785 // we need to find the item's position in the child list
787 wxMenuItemList::compatibility_iterator node
= GetMenuItems().GetFirst();
788 for ( pos
= 0; node
; pos
++ )
790 if ( node
->GetData() == item
)
793 node
= node
->GetNext();
796 // DoRemove() (unlike Remove) can only be called for an existing item!
797 wxCHECK_MSG( node
, NULL
, wxT("bug in wxMenu::Remove logic") );
800 // remove the corresponding accel from the accel table
801 int n
= FindAccel(item
->GetId());
802 if ( n
!= wxNOT_FOUND
)
806 m_accels
.RemoveAt(n
);
808 ResetMaxAccelWidth();
810 //else: this item doesn't have an accel, nothing to do
811 #endif // wxUSE_ACCEL
813 // remove the item from the menu
814 if ( !::RemoveMenu(GetHmenu(), (UINT
)pos
, MF_BYPOSITION
) )
816 wxLogLastError(wxT("RemoveMenu"));
819 if ( IsAttached() && GetMenuBar()->IsAttached() )
821 // otherwise, the change won't be visible
822 GetMenuBar()->Refresh();
825 // and from internal data structures
826 return wxMenuBase::DoRemove(item
);
829 // ---------------------------------------------------------------------------
830 // accelerator helpers
831 // ---------------------------------------------------------------------------
835 // create the wxAcceleratorEntries for our accels and put them into the provided
836 // array - return the number of accels we have
837 size_t wxMenu::CopyAccels(wxAcceleratorEntry
*accels
) const
839 size_t count
= GetAccelCount();
840 for ( size_t n
= 0; n
< count
; n
++ )
842 *accels
++ = *m_accels
[n
];
848 wxAcceleratorTable
*wxMenu::CreateAccelTable() const
850 const size_t count
= m_accels
.size();
851 wxScopedArray
<wxAcceleratorEntry
> accels(new wxAcceleratorEntry
[count
]);
852 CopyAccels(accels
.get());
854 return new wxAcceleratorTable(count
, accels
.get());
857 #endif // wxUSE_ACCEL
859 // ---------------------------------------------------------------------------
860 // ownerdrawn helpers
861 // ---------------------------------------------------------------------------
863 #if wxUSE_OWNER_DRAWN
865 void wxMenu::CalculateMaxAccelWidth()
867 wxASSERT_MSG( m_maxAccelWidth
== -1, wxT("it's really needed?") );
869 wxMenuItemList::compatibility_iterator node
= GetMenuItems().GetFirst();
872 wxMenuItem
* item
= node
->GetData();
874 if ( item
->IsOwnerDrawn() )
876 int width
= item
->MeasureAccelWidth();
877 if (width
> m_maxAccelWidth
)
878 m_maxAccelWidth
= width
;
881 node
= node
->GetNext();
885 #endif // wxUSE_OWNER_DRAWN
887 // ---------------------------------------------------------------------------
889 // ---------------------------------------------------------------------------
891 void wxMenu::SetTitle(const wxString
& label
)
893 bool hasNoTitle
= m_title
.empty();
896 HMENU hMenu
= GetHmenu();
900 if ( !label
.empty() )
902 if ( !::InsertMenu(hMenu
, 0u, MF_BYPOSITION
| MF_STRING
,
903 idMenuTitle
, m_title
.wx_str()) ||
904 !::InsertMenu(hMenu
, 1u, MF_BYPOSITION
, (unsigned)-1, NULL
) )
906 wxLogLastError(wxT("InsertMenu"));
914 // remove the title and the separator after it
915 if ( !RemoveMenu(hMenu
, 0, MF_BYPOSITION
) ||
916 !RemoveMenu(hMenu
, 0, MF_BYPOSITION
) )
918 wxLogLastError(wxT("RemoveMenu"));
927 info
.cbSize
= sizeof(info
);
928 info
.fMask
= MIIM_TYPE
;
929 info
.fType
= MFT_STRING
;
930 info
.cch
= m_title
.length();
931 info
.dwTypeData
= const_cast<wxChar
*>(m_title
.wx_str());
932 if ( !SetMenuItemInfo(hMenu
, 0, TRUE
, & info
) )
934 wxLogLastError(wxT("SetMenuItemInfo"));
937 if ( !ModifyMenu(hMenu
, 0u,
938 MF_BYPOSITION
| MF_STRING
,
939 idMenuTitle
, m_title
.wx_str()) )
941 wxLogLastError(wxT("ModifyMenu"));
948 // put the title string in bold face
949 if ( !m_title
.empty() )
951 SetDefaultMenuItem(GetHmenu(), idMenuTitle
);
956 // ---------------------------------------------------------------------------
958 // ---------------------------------------------------------------------------
960 bool wxMenu::MSWCommand(WXUINT
WXUNUSED(param
), WXWORD id_
)
962 const int id
= (signed short)id_
;
964 // ignore commands from the menu title
965 if ( id
!= (int)idMenuTitle
)
967 // update the check item when it's clicked
968 wxMenuItem
* const item
= FindItem(id
);
969 if ( item
&& item
->IsCheckable() )
972 // get the status of the menu item: note that it has been just changed
973 // by Toggle() above so here we already get the new state of the item
974 UINT menuState
= ::GetMenuState(GetHmenu(), id
, MF_BYCOMMAND
);
975 SendEvent(id
, menuState
& MF_CHECKED
);
981 // ---------------------------------------------------------------------------
983 // ---------------------------------------------------------------------------
985 wxWindow
*wxMenu::GetWindow() const
987 return GetMenuBar() ? GetMenuBar()->GetFrame() : GetInvokingWindow();
990 // ---------------------------------------------------------------------------
992 // ---------------------------------------------------------------------------
994 void wxMenuBar::Init()
996 m_eventHandler
= this;
998 #if wxUSE_TOOLBAR && defined(__WXWINCE__)
1001 // Not using a combined wxToolBar/wxMenuBar? then use
1002 // a commandbar in WinCE .NET just to implement the
1004 #if defined(WINCE_WITH_COMMANDBAR)
1005 m_commandBar
= NULL
;
1006 m_adornmentsAdded
= false;
1010 wxMenuBar::wxMenuBar()
1015 wxMenuBar::wxMenuBar( long WXUNUSED(style
) )
1020 wxMenuBar::wxMenuBar(size_t count
, wxMenu
*menus
[], const wxString titles
[], long WXUNUSED(style
))
1024 m_titles
.Alloc(count
);
1026 for ( size_t i
= 0; i
< count
; i
++ )
1028 m_menus
.Append(menus
[i
]);
1029 m_titles
.Add(titles
[i
]);
1031 menus
[i
]->Attach(this);
1035 wxMenuBar::~wxMenuBar()
1037 // In Windows CE (not .NET), the menubar is always associated
1038 // with a toolbar, which destroys the menu implicitly.
1039 #if defined(WINCE_WITHOUT_COMMANDBAR) && defined(__POCKETPC__)
1042 wxToolMenuBar
* toolMenuBar
= wxDynamicCast(GetToolBar(), wxToolMenuBar
);
1044 toolMenuBar
->SetMenuBar(NULL
);
1047 // we should free Windows resources only if Windows doesn't do it for us
1048 // which happens if we're attached to a frame
1049 if (m_hMenu
&& !IsAttached())
1051 #if defined(WINCE_WITH_COMMANDBAR)
1052 ::DestroyWindow((HWND
) m_commandBar
);
1053 m_commandBar
= (WXHWND
) NULL
;
1055 ::DestroyMenu((HMENU
)m_hMenu
);
1057 m_hMenu
= (WXHMENU
)NULL
;
1062 // ---------------------------------------------------------------------------
1063 // wxMenuBar helpers
1064 // ---------------------------------------------------------------------------
1066 void wxMenuBar::Refresh()
1071 wxCHECK_RET( IsAttached(), wxT("can't refresh unattached menubar") );
1073 #if defined(WINCE_WITHOUT_COMMANDBAR)
1076 CommandBar_DrawMenuBar((HWND
) GetToolBar()->GetHWND(), 0);
1078 #elif defined(WINCE_WITH_COMMANDBAR)
1080 DrawMenuBar((HWND
) m_commandBar
);
1082 DrawMenuBar(GetHwndOf(GetFrame()));
1086 WXHMENU
wxMenuBar::Create()
1088 // Note: this doesn't work at all on Smartphone,
1089 // since you have to use resources.
1090 // We'll have to find another way to add a menu
1091 // by changing/adding menu items to an existing menu.
1092 #if defined(WINCE_WITHOUT_COMMANDBAR)
1096 wxToolMenuBar
* const bar
= static_cast<wxToolMenuBar
*>(GetToolBar());
1100 HWND hCommandBar
= GetHwndOf(bar
);
1102 // notify comctl32.dll about the version of the headers we use before using
1103 // any other TB_XXX messages
1104 SendMessage(hCommandBar
, TB_BUTTONSTRUCTSIZE
, sizeof(TBBUTTON
), 0);
1107 wxZeroMemory(tbButton
);
1108 tbButton
.iBitmap
= I_IMAGENONE
;
1109 tbButton
.fsState
= TBSTATE_ENABLED
;
1110 tbButton
.fsStyle
= TBSTYLE_DROPDOWN
|
1111 TBSTYLE_NO_DROPDOWN_ARROW
|
1114 for ( unsigned i
= 0; i
< GetMenuCount(); i
++ )
1116 HMENU hPopupMenu
= (HMENU
) GetMenu(i
)->GetHMenu();
1117 tbButton
.dwData
= (DWORD
)hPopupMenu
;
1118 wxString label
= wxStripMenuCodes(GetMenuLabel(i
));
1119 tbButton
.iString
= (int) label
.wx_str();
1121 tbButton
.idCommand
= NewControlId();
1122 if ( !::SendMessage(hCommandBar
, TB_INSERTBUTTON
, i
, (LPARAM
)&tbButton
) )
1124 wxLogLastError(wxT("TB_INSERTBUTTON"));
1128 m_hMenu
= bar
->GetHMenu();
1130 #else // !__WXWINCE__
1134 m_hMenu
= (WXHMENU
)::CreateMenu();
1138 wxLogLastError(wxT("CreateMenu"));
1142 size_t count
= GetMenuCount(), i
;
1143 wxMenuList::iterator it
;
1144 for ( i
= 0, it
= m_menus
.begin(); i
< count
; i
++, it
++ )
1146 if ( !::AppendMenu((HMENU
)m_hMenu
, MF_POPUP
| MF_STRING
,
1147 (UINT_PTR
)(*it
)->GetHMenu(),
1148 m_titles
[i
].wx_str()) )
1150 wxLogLastError(wxT("AppendMenu"));
1156 #endif // __WXWINCE__/!__WXWINCE__
1159 int wxMenuBar::MSWPositionForWxMenu(wxMenu
*menu
, int wxpos
)
1162 wxASSERT(menu
->GetHMenu());
1165 #if defined(__WXWINCE__)
1166 int totalMSWItems
= GetMenuCount();
1168 int totalMSWItems
= GetMenuItemCount((HMENU
)m_hMenu
);
1171 int i
; // For old C++ compatibility
1172 for(i
=wxpos
; i
<totalMSWItems
; i
++)
1174 if(GetSubMenu((HMENU
)m_hMenu
,i
)==(HMENU
)menu
->GetHMenu())
1177 for(i
=0; i
<wxpos
; i
++)
1179 if(GetSubMenu((HMENU
)m_hMenu
,i
)==(HMENU
)menu
->GetHMenu())
1186 // ---------------------------------------------------------------------------
1187 // wxMenuBar functions to work with the top level submenus
1188 // ---------------------------------------------------------------------------
1190 // NB: we don't support owner drawn top level items for now, if we do these
1191 // functions would have to be changed to use wxMenuItem as well
1193 void wxMenuBar::EnableTop(size_t pos
, bool enable
)
1195 wxCHECK_RET( IsAttached(), wxT("doesn't work with unattached menubars") );
1196 wxCHECK_RET( pos
< GetMenuCount(), wxT("invalid menu index") );
1198 int flag
= enable
? MF_ENABLED
: MF_GRAYED
;
1200 EnableMenuItem((HMENU
)m_hMenu
, MSWPositionForWxMenu(GetMenu(pos
),pos
), MF_BYPOSITION
| flag
);
1205 void wxMenuBar::SetMenuLabel(size_t pos
, const wxString
& label
)
1207 wxCHECK_RET( pos
< GetMenuCount(), wxT("invalid menu index") );
1209 m_titles
[pos
] = label
;
1211 if ( !IsAttached() )
1215 //else: have to modify the existing menu
1217 int mswpos
= MSWPositionForWxMenu(GetMenu(pos
),pos
);
1220 UINT flagsOld
= ::GetMenuState((HMENU
)m_hMenu
, mswpos
, MF_BYPOSITION
);
1221 if ( flagsOld
== 0xFFFFFFFF )
1223 wxLogLastError(wxT("GetMenuState"));
1228 if ( flagsOld
& MF_POPUP
)
1230 // HIBYTE contains the number of items in the submenu in this case
1232 id
= (UINT_PTR
)::GetSubMenu((HMENU
)m_hMenu
, mswpos
);
1242 info
.cbSize
= sizeof(info
);
1243 info
.fMask
= MIIM_TYPE
;
1244 info
.fType
= MFT_STRING
;
1245 info
.cch
= label
.length();
1246 info
.dwTypeData
= const_cast<wxChar
*>(label
.wx_str());
1247 if ( !SetMenuItemInfo(GetHmenu(), id
, TRUE
, &info
) )
1249 wxLogLastError(wxT("SetMenuItemInfo"));
1253 if ( ::ModifyMenu(GetHmenu(), mswpos
, MF_BYPOSITION
| MF_STRING
| flagsOld
,
1254 id
, label
.wx_str()) == (int)0xFFFFFFFF )
1256 wxLogLastError(wxT("ModifyMenu"));
1263 wxString
wxMenuBar::GetMenuLabel(size_t pos
) const
1265 wxCHECK_MSG( pos
< GetMenuCount(), wxEmptyString
,
1266 wxT("invalid menu index in wxMenuBar::GetMenuLabel") );
1268 return m_titles
[pos
];
1271 // ---------------------------------------------------------------------------
1272 // wxMenuBar construction
1273 // ---------------------------------------------------------------------------
1275 wxMenu
*wxMenuBar::Replace(size_t pos
, wxMenu
*menu
, const wxString
& title
)
1277 wxMenu
*menuOld
= wxMenuBarBase::Replace(pos
, menu
, title
);
1281 m_titles
[pos
] = title
;
1283 #if defined(WINCE_WITHOUT_COMMANDBAR)
1289 int mswpos
= MSWPositionForWxMenu(menuOld
,pos
);
1291 // can't use ModifyMenu() because it deletes the submenu it replaces
1292 if ( !::RemoveMenu(GetHmenu(), (UINT
)mswpos
, MF_BYPOSITION
) )
1294 wxLogLastError(wxT("RemoveMenu"));
1297 if ( !::InsertMenu(GetHmenu(), (UINT
)mswpos
,
1298 MF_BYPOSITION
| MF_POPUP
| MF_STRING
,
1299 (UINT_PTR
)GetHmenuOf(menu
), title
.wx_str()) )
1301 wxLogLastError(wxT("InsertMenu"));
1305 if ( menuOld
->HasAccels() || menu
->HasAccels() )
1307 // need to rebuild accell table
1308 RebuildAccelTable();
1310 #endif // wxUSE_ACCEL
1319 bool wxMenuBar::Insert(size_t pos
, wxMenu
*menu
, const wxString
& title
)
1321 // Find out which MSW item before which we'll be inserting before
1322 // wxMenuBarBase::Insert is called and GetMenu(pos) is the new menu.
1323 // If IsAttached() is false this won't be used anyway
1325 #if defined(WINCE_WITHOUT_COMMANDBAR)
1331 int mswpos
= (!isAttached
|| (pos
== m_menus
.GetCount()))
1332 ? -1 // append the menu
1333 : MSWPositionForWxMenu(GetMenu(pos
),pos
);
1335 if ( !wxMenuBarBase::Insert(pos
, menu
, title
) )
1338 m_titles
.Insert(title
, pos
);
1342 #if defined(WINCE_WITHOUT_COMMANDBAR)
1346 memset(&tbButton
, 0, sizeof(TBBUTTON
));
1347 tbButton
.iBitmap
= I_IMAGENONE
;
1348 tbButton
.fsState
= TBSTATE_ENABLED
;
1349 tbButton
.fsStyle
= TBSTYLE_DROPDOWN
| TBSTYLE_NO_DROPDOWN_ARROW
| TBSTYLE_AUTOSIZE
;
1351 HMENU hPopupMenu
= (HMENU
) menu
->GetHMenu() ;
1352 tbButton
.dwData
= (DWORD
)hPopupMenu
;
1353 wxString label
= wxStripMenuCodes(title
);
1354 tbButton
.iString
= (int) label
.wx_str();
1356 tbButton
.idCommand
= NewControlId();
1357 if (!::SendMessage((HWND
) GetToolBar()->GetHWND(), TB_INSERTBUTTON
, pos
, (LPARAM
)&tbButton
))
1359 wxLogLastError(wxT("TB_INSERTBUTTON"));
1362 wxUnusedVar(mswpos
);
1364 if ( !::InsertMenu(GetHmenu(), mswpos
,
1365 MF_BYPOSITION
| MF_POPUP
| MF_STRING
,
1366 (UINT_PTR
)GetHmenuOf(menu
), title
.wx_str()) )
1368 wxLogLastError(wxT("InsertMenu"));
1372 if ( menu
->HasAccels() )
1374 // need to rebuild accell table
1375 RebuildAccelTable();
1377 #endif // wxUSE_ACCEL
1386 bool wxMenuBar::Append(wxMenu
*menu
, const wxString
& title
)
1388 WXHMENU submenu
= menu
? menu
->GetHMenu() : 0;
1389 wxCHECK_MSG( submenu
, false, wxT("can't append invalid menu to menubar") );
1391 if ( !wxMenuBarBase::Append(menu
, title
) )
1394 m_titles
.Add(title
);
1396 #if defined(WINCE_WITHOUT_COMMANDBAR)
1402 #if defined(WINCE_WITHOUT_COMMANDBAR)
1406 memset(&tbButton
, 0, sizeof(TBBUTTON
));
1407 tbButton
.iBitmap
= I_IMAGENONE
;
1408 tbButton
.fsState
= TBSTATE_ENABLED
;
1409 tbButton
.fsStyle
= TBSTYLE_DROPDOWN
| TBSTYLE_NO_DROPDOWN_ARROW
| TBSTYLE_AUTOSIZE
;
1411 size_t pos
= GetMenuCount();
1412 HMENU hPopupMenu
= (HMENU
) menu
->GetHMenu() ;
1413 tbButton
.dwData
= (DWORD
)hPopupMenu
;
1414 wxString label
= wxStripMenuCodes(title
);
1415 tbButton
.iString
= (int) label
.wx_str();
1417 tbButton
.idCommand
= NewControlId();
1418 if (!::SendMessage((HWND
) GetToolBar()->GetHWND(), TB_INSERTBUTTON
, pos
, (LPARAM
)&tbButton
))
1420 wxLogLastError(wxT("TB_INSERTBUTTON"));
1424 if ( !::AppendMenu(GetHmenu(), MF_POPUP
| MF_STRING
,
1425 (UINT_PTR
)submenu
, title
.wx_str()) )
1427 wxLogLastError(wxT("AppendMenu"));
1432 if ( menu
->HasAccels() )
1434 // need to rebuild accelerator table
1435 RebuildAccelTable();
1437 #endif // wxUSE_ACCEL
1446 wxMenu
*wxMenuBar::Remove(size_t pos
)
1448 wxMenu
*menu
= wxMenuBarBase::Remove(pos
);
1452 #if defined(WINCE_WITHOUT_COMMANDBAR)
1458 #if defined(WINCE_WITHOUT_COMMANDBAR)
1461 if (!::SendMessage((HWND
) GetToolBar()->GetHWND(), TB_DELETEBUTTON
, (UINT
) pos
, (LPARAM
) 0))
1463 wxLogLastError(wxT("TB_DELETEBUTTON"));
1467 if ( !::RemoveMenu(GetHmenu(), (UINT
)MSWPositionForWxMenu(menu
,pos
), MF_BYPOSITION
) )
1469 wxLogLastError(wxT("RemoveMenu"));
1474 if ( menu
->HasAccels() )
1476 // need to rebuild accell table
1477 RebuildAccelTable();
1479 #endif // wxUSE_ACCEL
1485 m_titles
.RemoveAt(pos
);
1492 void wxMenuBar::RebuildAccelTable()
1494 // merge the accelerators of all menus into one accel table
1495 size_t nAccelCount
= 0;
1496 size_t i
, count
= GetMenuCount();
1497 wxMenuList::iterator it
;
1498 for ( i
= 0, it
= m_menus
.begin(); i
< count
; i
++, it
++ )
1500 nAccelCount
+= (*it
)->GetAccelCount();
1505 wxAcceleratorEntry
*accelEntries
= new wxAcceleratorEntry
[nAccelCount
];
1508 for ( i
= 0, it
= m_menus
.begin(); i
< count
; i
++, it
++ )
1510 nAccelCount
+= (*it
)->CopyAccels(&accelEntries
[nAccelCount
]);
1513 SetAcceleratorTable(wxAcceleratorTable(nAccelCount
, accelEntries
));
1515 delete [] accelEntries
;
1519 #endif // wxUSE_ACCEL
1521 void wxMenuBar::Attach(wxFrame
*frame
)
1523 wxMenuBarBase::Attach(frame
);
1525 #if defined(WINCE_WITH_COMMANDBAR)
1529 m_commandBar
= (WXHWND
) CommandBar_Create(wxGetInstance(), (HWND
) frame
->GetHWND(), NewControlId());
1534 if (!CommandBar_InsertMenubarEx((HWND
) m_commandBar
, NULL
, (LPTSTR
) m_hMenu
, 0))
1536 wxLogLastError(wxT("CommandBar_InsertMenubarEx"));
1543 RebuildAccelTable();
1544 #endif // wxUSE_ACCEL
1547 #if defined(WINCE_WITH_COMMANDBAR)
1548 bool wxMenuBar::AddAdornments(long style
)
1550 if (m_adornmentsAdded
|| !m_commandBar
)
1553 if (style
& wxCLOSE_BOX
)
1555 if (!CommandBar_AddAdornments((HWND
) m_commandBar
, 0, 0))
1557 wxLogLastError(wxT("CommandBar_AddAdornments"));
1568 void wxMenuBar::Detach()
1570 wxMenuBarBase::Detach();
1573 #endif // wxUSE_MENUS