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"
44 #include "wx/vector.h"
46 #include "wx/msw/private.h"
47 #include "wx/msw/wrapcctl.h" // include <commctrl.h> "properly"
55 #if (_WIN32_WCE < 400) && !defined(__HANDHELDPC__)
59 #include "wx/msw/wince/missing.h"
63 // other standard headers
67 #include "wx/dynlib.h"
70 #ifndef MNS_CHECKORBMP
71 #define MNS_CHECKORBMP 0x04000000
74 #define MIM_STYLE 0x00000010
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
81 // ----------------------------------------------------------------------------
83 // ----------------------------------------------------------------------------
85 // the (popup) menu title has this special id
86 static const int idMenuTitle
= wxID_NONE
;
88 // ----------------------------------------------------------------------------
89 // private helper classes and functions
90 // ----------------------------------------------------------------------------
92 // Contains the data about the radio items groups in the given menu.
93 class wxMenuRadioItemsData
96 wxMenuRadioItemsData() { }
98 // Default copy ctor, assignment operator and dtor are all ok.
100 // Find the start and end of the group containing the given position or
101 // return false if it's not inside any range.
102 bool GetGroupRange(int pos
, int *start
, int *end
) const
104 // We use a simple linear search here because there are not that many
105 // items in a menu and hence even fewer radio items ranges anyhow, so
106 // normally there is no need to do anything fancy (like keeping the
107 // array sorted and using binary search).
108 for ( Ranges::const_iterator it
= m_ranges
.begin();
109 it
!= m_ranges
.end();
112 const Range
& r
= *it
;
114 if ( r
.start
<= pos
&& pos
<= r
.end
)
128 // Take into account the new radio item about to be added at the given
131 // Returns true if this item starts a new radio group, false if it extends
133 bool UpdateOnInsert(int pos
)
135 bool inExistingGroup
= false;
137 for ( Ranges::iterator it
= m_ranges
.begin();
138 it
!= m_ranges
.end();
145 // Item is inserted before this range, update its indices.
149 else if ( pos
<= r
.end
+ 1 )
151 // Item is inserted in the middle of this range or immediately
152 // after it in which case it extends this range so make it span
153 // one more item in any case.
156 inExistingGroup
= true;
158 //else: Item is inserted after this range, nothing to do for it.
161 if ( inExistingGroup
)
164 // Make a new range for the group this item will belong to.
168 m_ranges
.push_back(r
);
174 // Contains the inclusive positions of the range start and end.
181 typedef wxVector
<Range
> Ranges
;
188 // make the given menu item default
189 void SetDefaultMenuItem(HMENU
WXUNUSED_IN_WINCE(hmenu
),
190 UINT
WXUNUSED_IN_WINCE(id
))
193 WinStruct
<MENUITEMINFO
> mii
;
194 mii
.fMask
= MIIM_STATE
;
195 mii
.fState
= MFS_DEFAULT
;
197 if ( !::SetMenuItemInfo(hmenu
, id
, FALSE
, &mii
) )
199 wxLogLastError(wxT("SetMenuItemInfo"));
201 #endif // !__WXWINCE__
204 // make the given menu item owner-drawn
205 void SetOwnerDrawnMenuItem(HMENU
WXUNUSED_IN_WINCE(hmenu
),
206 UINT
WXUNUSED_IN_WINCE(id
),
207 ULONG_PTR
WXUNUSED_IN_WINCE(data
),
208 BOOL
WXUNUSED_IN_WINCE(byPositon
= FALSE
))
211 WinStruct
<MENUITEMINFO
> mii
;
212 mii
.fMask
= MIIM_FTYPE
| MIIM_DATA
;
213 mii
.fType
= MFT_OWNERDRAW
;
214 mii
.dwItemData
= data
;
216 if ( reinterpret_cast<wxMenuItem
*>(data
)->IsSeparator() )
217 mii
.fType
|= MFT_SEPARATOR
;
219 if ( !::SetMenuItemInfo(hmenu
, id
, byPositon
, &mii
) )
221 wxLogLastError(wxT("SetMenuItemInfo"));
223 #endif // !__WXWINCE__
227 UINT
GetMenuState(HMENU hMenu
, UINT id
, UINT flags
)
229 WinStruct
<MENUITEMINFO
> info
;
230 info
.fMask
= MIIM_STATE
;
231 // MF_BYCOMMAND is zero so test MF_BYPOSITION
232 if ( !::GetMenuItemInfo(hMenu
, id
, flags
& MF_BYPOSITION
? TRUE
: FALSE
, & info
) )
234 wxLogLastError(wxT("GetMenuItemInfo"));
238 #endif // __WXWINCE__
240 inline bool IsGreaterThanStdSize(const wxBitmap
& bmp
)
242 return bmp
.GetWidth() > ::GetSystemMetrics(SM_CXMENUCHECK
) ||
243 bmp
.GetHeight() > ::GetSystemMetrics(SM_CYMENUCHECK
);
246 } // anonymous namespace
248 // ============================================================================
250 // ============================================================================
252 // ---------------------------------------------------------------------------
253 // wxMenu construction, adding and removing menu items
254 // ---------------------------------------------------------------------------
256 // Construct a menu with optional title (then use append)
257 void wxMenu::InitNoCreate()
262 #if wxUSE_OWNER_DRAWN
263 m_ownerDrawn
= false;
264 m_maxBitmapWidth
= 0;
265 m_maxAccelWidth
= -1;
266 #endif // wxUSE_OWNER_DRAWN
274 m_hMenu
= (WXHMENU
)CreatePopupMenu();
277 wxLogLastError(wxT("CreatePopupMenu"));
280 // if we have a title, insert it in the beginning of the menu
281 if ( !m_title
.empty() )
283 const wxString title
= m_title
;
284 m_title
.clear(); // so that SetTitle() knows there was no title before
289 wxMenu::wxMenu(WXHMENU hMenu
)
295 // Ensure that our internal idea of how many items we have corresponds to
296 // the real number of items in the menu.
298 // We could also retrieve the real labels of the items here but it doesn't
299 // seem to be worth the trouble.
300 const int numExistingItems
= ::GetMenuItemCount(m_hMenu
);
301 for ( int n
= 0; n
< numExistingItems
; n
++ )
303 wxMenuBase::DoAppend(wxMenuItem::New(this, wxID_SEPARATOR
));
307 // The wxWindow destructor will take care of deleting the submenus.
310 // we should free Windows resources only if Windows doesn't do it for us
311 // which happens if we're attached to a menubar or a submenu of another
313 if ( !IsAttached() && !GetParent() )
315 if ( !::DestroyMenu(GetHmenu()) )
317 wxLogLastError(wxT("DestroyMenu"));
323 WX_CLEAR_ARRAY(m_accels
);
324 #endif // wxUSE_ACCEL
331 // this will take effect during the next call to Append()
337 int wxMenu::FindAccel(int id
) const
339 size_t n
, count
= m_accels
.GetCount();
340 for ( n
= 0; n
< count
; n
++ )
342 if ( m_accels
[n
]->m_command
== id
)
349 void wxMenu::UpdateAccel(wxMenuItem
*item
)
351 if ( item
->IsSubMenu() )
353 wxMenu
*submenu
= item
->GetSubMenu();
354 wxMenuItemList::compatibility_iterator node
= submenu
->GetMenuItems().GetFirst();
357 UpdateAccel(node
->GetData());
359 node
= node
->GetNext();
362 else if ( !item
->IsSeparator() )
364 // recurse upwards: we should only modify m_accels of the top level
365 // menus, not of the submenus as wxMenuBar doesn't look at them
366 // (alternative and arguable cleaner solution would be to recurse
367 // downwards in GetAccelCount() and CopyAccels())
370 GetParent()->UpdateAccel(item
);
374 // find the (new) accel for this item
375 wxAcceleratorEntry
*accel
= wxAcceleratorEntry::Create(item
->GetItemLabel());
377 accel
->m_command
= item
->GetId();
380 int n
= FindAccel(item
->GetId());
381 if ( n
== wxNOT_FOUND
)
383 // no old, add new if any
387 return; // skipping RebuildAccelTable() below
391 // replace old with new or just remove the old one if no new
396 m_accels
.RemoveAt(n
);
401 GetMenuBar()->RebuildAccelTable();
404 #if wxUSE_OWNER_DRAWN
405 ResetMaxAccelWidth();
408 //else: it is a separator, they can't have accels, nothing to do
411 #endif // wxUSE_ACCEL
416 // helper of DoInsertOrAppend(): returns the HBITMAP to use in MENUITEMINFO
417 HBITMAP
GetHBitmapForMenu(wxMenuItem
*pItem
, bool checked
= true)
419 // Under versions of Windows older than Vista we can't pass HBITMAP
420 // directly as hbmpItem for 2 reasons:
421 // 1. We can't draw it with transparency then (this is not
422 // very important now but would be with themed menu bg)
423 // 2. Worse, Windows inverts the bitmap for the selected
424 // item and this looks downright ugly
426 // So we prefer to instead draw it ourselves in MSWOnDrawItem().by using
427 // HBMMENU_CALLBACK when inserting it
429 // However under Vista using HBMMENU_CALLBACK causes the entire menu to be
430 // drawn using the classic theme instead of the current one and it does
431 // handle transparency just fine so do use the real bitmap there
433 if ( wxGetWinVersion() >= wxWinVersion_Vista
)
435 #if wxUSE_OWNER_DRAWN
436 wxBitmap bmp
= pItem
->GetBitmap(checked
);
439 // we must use PARGB DIB for the menu bitmaps so ensure that we do
440 wxImage
img(bmp
.ConvertToImage());
441 if ( !img
.HasAlpha() )
444 pItem
->SetBitmap(img
, checked
);
447 return GetHbitmapOf(pItem
->GetBitmap(checked
));
449 #endif // wxUSE_OWNER_DRAWN
450 //else: bitmap is not set
454 #endif // wxUSE_IMAGE
456 return HBMMENU_CALLBACK
;
459 } // anonymous namespace
461 bool wxMenu::MSWGetRadioGroupRange(int pos
, int *start
, int *end
) const
463 return m_radioData
&& m_radioData
->GetGroupRange(pos
, start
, end
);
466 // append a new item or submenu to the menu
467 bool wxMenu::DoInsertOrAppend(wxMenuItem
*pItem
, size_t pos
)
471 #endif // wxUSE_ACCEL
473 // we should support disabling the item even prior to adding it to the menu
474 UINT flags
= pItem
->IsEnabled() ? MF_ENABLED
: MF_GRAYED
;
476 // if "Break" has just been called, insert a menu break before this item
477 // (and don't forget to reset the flag)
479 flags
|= MF_MENUBREAK
;
483 if ( pItem
->IsSeparator() ) {
484 flags
|= MF_SEPARATOR
;
487 // id is the numeric id for normal menu items and HMENU for submenus as
488 // required by ::AppendMenu() API
490 wxMenu
*submenu
= pItem
->GetSubMenu();
491 if ( submenu
!= NULL
) {
492 wxASSERT_MSG( submenu
->GetHMenu(), wxT("invalid submenu") );
494 submenu
->SetParent(this);
496 id
= (UINT_PTR
)submenu
->GetHMenu();
501 id
= pItem
->GetMSWId();
505 // prepare to insert the item in the menu
506 wxString itemText
= pItem
->GetItemLabel();
507 LPCTSTR pData
= NULL
;
508 if ( pos
== (size_t)-1 )
510 // append at the end (note that the item is already appended to
511 // internal data structures)
512 pos
= GetMenuItemCount() - 1;
515 // Update radio groups data if we're inserting a new radio item.
517 // NB: If we supported inserting non-radio items in the middle of existing
518 // radio groups to break them into two subgroups, we'd need to update
519 // m_radioData in this case too but currently this is not supported.
520 bool checkInitially
= false;
521 if ( pItem
->GetKind() == wxITEM_RADIO
)
524 m_radioData
= new wxMenuRadioItemsData
;
526 if ( m_radioData
->UpdateOnInsert(pos
) )
527 checkInitially
= true;
530 // adjust position to account for the title of a popup menu, if any
531 if ( !GetMenuBar() && !m_title
.empty() )
532 pos
+= 2; // for the title itself and its separator
536 #if wxUSE_OWNER_DRAWN
537 // Under older systems mixing owner-drawn and non-owner-drawn items results
538 // in inconsistent margins, so we force this one to be owner-drawn if any
539 // other items already are.
541 pItem
->SetOwnerDrawn(true);
542 #endif // wxUSE_OWNER_DRAWN
544 // check if we have something more than a simple text item
545 #if wxUSE_OWNER_DRAWN
546 if ( pItem
->IsOwnerDrawn() )
550 if ( !m_ownerDrawn
&& !pItem
->IsSeparator() )
552 // MIIM_BITMAP only works under WinME/2000+ so we always use owner
553 // drawn item under the previous versions and we also have to use
554 // them in any case if the item has custom colours or font
555 static const wxWinVersion winver
= wxGetWinVersion();
556 bool mustUseOwnerDrawn
= winver
< wxWinVersion_98
||
557 pItem
->GetTextColour().IsOk() ||
558 pItem
->GetBackgroundColour().IsOk() ||
559 pItem
->GetFont().IsOk();
561 if ( !mustUseOwnerDrawn
)
563 const wxBitmap
& bmpUnchecked
= pItem
->GetBitmap(false),
564 bmpChecked
= pItem
->GetBitmap(true);
566 if ( (bmpUnchecked
.IsOk() && IsGreaterThanStdSize(bmpUnchecked
)) ||
567 (bmpChecked
.IsOk() && IsGreaterThanStdSize(bmpChecked
)) )
569 mustUseOwnerDrawn
= true;
573 // use InsertMenuItem() if possible as it's guaranteed to look
574 // correct while our owner-drawn code is not
575 if ( !mustUseOwnerDrawn
)
577 WinStruct
<MENUITEMINFO
> mii
;
578 mii
.fMask
= MIIM_STRING
| MIIM_DATA
;
580 // don't set hbmpItem for the checkable items as it would
581 // be used for both checked and unchecked state
582 if ( pItem
->IsCheckable() )
584 mii
.fMask
|= MIIM_CHECKMARKS
;
585 mii
.hbmpChecked
= GetHBitmapForMenu(pItem
, true);
586 mii
.hbmpUnchecked
= GetHBitmapForMenu(pItem
, false);
588 else if ( pItem
->GetBitmap().IsOk() )
590 mii
.fMask
|= MIIM_BITMAP
;
591 mii
.hbmpItem
= GetHBitmapForMenu(pItem
);
594 mii
.cch
= itemText
.length();
595 mii
.dwTypeData
= const_cast<wxChar
*>(itemText
.wx_str());
597 if ( flags
& MF_POPUP
)
599 mii
.fMask
|= MIIM_SUBMENU
;
600 mii
.hSubMenu
= GetHmenuOf(pItem
->GetSubMenu());
604 mii
.fMask
|= MIIM_ID
;
608 mii
.dwItemData
= reinterpret_cast<ULONG_PTR
>(pItem
);
610 ok
= ::InsertMenuItem(GetHmenu(), pos
, TRUE
/* by pos */, &mii
);
613 wxLogLastError(wxT("InsertMenuItem()"));
615 else // InsertMenuItem() ok
617 // we need to remove the extra indent which is reserved for
618 // the checkboxes by default as it looks ugly unless check
619 // boxes are used together with bitmaps and this is not the
621 WinStruct
<MENUINFO
> mi
;
623 // don't call SetMenuInfo() directly, this would prevent
624 // the app from starting up under Windows 95/NT 4
625 typedef BOOL (WINAPI
*SetMenuInfo_t
)(HMENU
, MENUINFO
*);
627 wxDynamicLibrary
dllUser(wxT("user32"));
628 wxDYNLIB_FUNCTION(SetMenuInfo_t
, SetMenuInfo
, dllUser
);
629 if ( pfnSetMenuInfo
)
631 mi
.fMask
= MIM_STYLE
;
632 mi
.dwStyle
= MNS_CHECKORBMP
;
633 if ( !(*pfnSetMenuInfo
)(GetHmenu(), &mi
) )
635 wxLogLastError(wxT("SetMenuInfo(MNS_NOCHECK)"));
639 // tell the item that it's not really owner-drawn but only
640 // needs to draw its bitmap, the rest is done by Windows
641 pItem
->SetOwnerDrawn(false);
649 // item draws itself, pass pointer to it in data parameter
650 flags
|= MF_OWNERDRAW
;
651 pData
= (LPCTSTR
)pItem
;
653 bool updateAllMargins
= false;
655 // get size of bitmap always return valid value (0 for invalid bitmap),
656 // so we don't needed check if bitmap is valid ;)
657 int uncheckedW
= pItem
->GetBitmap(false).GetWidth();
658 int checkedW
= pItem
->GetBitmap(true).GetWidth();
660 if ( m_maxBitmapWidth
< uncheckedW
)
662 m_maxBitmapWidth
= uncheckedW
;
663 updateAllMargins
= true;
666 if ( m_maxBitmapWidth
< checkedW
)
668 m_maxBitmapWidth
= checkedW
;
669 updateAllMargins
= true;
672 // make other item ownerdrawn and update margin width for equals alignment
673 if ( !m_ownerDrawn
|| updateAllMargins
)
675 // we must use position in SetOwnerDrawnMenuItem because
676 // all separators have the same id
678 wxMenuItemList::compatibility_iterator node
= GetMenuItems().GetFirst();
681 wxMenuItem
* item
= node
->GetData();
683 if ( !item
->IsOwnerDrawn())
685 item
->SetOwnerDrawn(true);
686 SetOwnerDrawnMenuItem(GetHmenu(), pos
,
687 reinterpret_cast<ULONG_PTR
>(item
), TRUE
);
690 item
->SetMarginWidth(m_maxBitmapWidth
);
692 node
= node
->GetNext();
696 // set menu as ownerdrawn
699 ResetMaxAccelWidth();
701 // only update our margin for equals alignment to other item
702 else if ( !updateAllMargins
)
704 pItem
->SetMarginWidth(m_maxBitmapWidth
);
709 #endif // wxUSE_OWNER_DRAWN
711 // item is just a normal string (passed in data parameter)
715 itemText
= wxMenuItem::GetLabelText(itemText
);
718 pData
= (wxChar
*)itemText
.wx_str();
721 // item might have already been inserted by InsertMenuItem() above
724 if ( !::InsertMenu(GetHmenu(), pos
, flags
| MF_BYPOSITION
, id
, pData
) )
726 wxLogLastError(wxT("InsertMenu[Item]()"));
733 // Check the item if it should be initially checked.
734 if ( checkInitially
)
737 // if we just appended the title, highlight it
738 if ( id
== (UINT_PTR
)idMenuTitle
)
740 // visually select the menu title
741 SetDefaultMenuItem(GetHmenu(), id
);
744 // if we're already attached to the menubar, we must update it
745 if ( IsAttached() && GetMenuBar()->IsAttached() )
747 GetMenuBar()->Refresh();
753 wxMenuItem
* wxMenu::DoAppend(wxMenuItem
*item
)
755 return wxMenuBase::DoAppend(item
) && DoInsertOrAppend(item
) ? item
: NULL
;
758 wxMenuItem
* wxMenu::DoInsert(size_t pos
, wxMenuItem
*item
)
760 if (wxMenuBase::DoInsert(pos
, item
) && DoInsertOrAppend(item
, pos
))
766 wxMenuItem
*wxMenu::DoRemove(wxMenuItem
*item
)
768 // we need to find the item's position in the child list
770 wxMenuItemList::compatibility_iterator node
= GetMenuItems().GetFirst();
771 for ( pos
= 0; node
; pos
++ )
773 if ( node
->GetData() == item
)
776 node
= node
->GetNext();
779 // DoRemove() (unlike Remove) can only be called for an existing item!
780 wxCHECK_MSG( node
, NULL
, wxT("bug in wxMenu::Remove logic") );
783 // remove the corresponding accel from the accel table
784 int n
= FindAccel(item
->GetId());
785 if ( n
!= wxNOT_FOUND
)
789 m_accels
.RemoveAt(n
);
791 #if wxUSE_OWNER_DRAWN
792 ResetMaxAccelWidth();
795 //else: this item doesn't have an accel, nothing to do
796 #endif // wxUSE_ACCEL
798 // remove the item from the menu
799 if ( !::RemoveMenu(GetHmenu(), (UINT
)pos
, MF_BYPOSITION
) )
801 wxLogLastError(wxT("RemoveMenu"));
804 if ( IsAttached() && GetMenuBar()->IsAttached() )
806 // otherwise, the change won't be visible
807 GetMenuBar()->Refresh();
810 // and from internal data structures
811 return wxMenuBase::DoRemove(item
);
814 // ---------------------------------------------------------------------------
815 // accelerator helpers
816 // ---------------------------------------------------------------------------
820 // create the wxAcceleratorEntries for our accels and put them into the provided
821 // array - return the number of accels we have
822 size_t wxMenu::CopyAccels(wxAcceleratorEntry
*accels
) const
824 size_t count
= GetAccelCount();
825 for ( size_t n
= 0; n
< count
; n
++ )
827 *accels
++ = *m_accels
[n
];
833 wxAcceleratorTable
*wxMenu::CreateAccelTable() const
835 const size_t count
= m_accels
.size();
836 wxScopedArray
<wxAcceleratorEntry
> accels(new wxAcceleratorEntry
[count
]);
837 CopyAccels(accels
.get());
839 return new wxAcceleratorTable(count
, accels
.get());
842 #endif // wxUSE_ACCEL
844 // ---------------------------------------------------------------------------
845 // ownerdrawn helpers
846 // ---------------------------------------------------------------------------
848 #if wxUSE_OWNER_DRAWN
850 void wxMenu::CalculateMaxAccelWidth()
852 wxASSERT_MSG( m_maxAccelWidth
== -1, wxT("it's really needed?") );
854 wxMenuItemList::compatibility_iterator node
= GetMenuItems().GetFirst();
857 wxMenuItem
* item
= node
->GetData();
859 if ( item
->IsOwnerDrawn() )
861 int width
= item
->MeasureAccelWidth();
862 if (width
> m_maxAccelWidth
)
863 m_maxAccelWidth
= width
;
866 node
= node
->GetNext();
870 #endif // wxUSE_OWNER_DRAWN
872 // ---------------------------------------------------------------------------
874 // ---------------------------------------------------------------------------
876 void wxMenu::SetTitle(const wxString
& label
)
878 bool hasNoTitle
= m_title
.empty();
881 HMENU hMenu
= GetHmenu();
885 if ( !label
.empty() )
887 if ( !::InsertMenu(hMenu
, 0u, MF_BYPOSITION
| MF_STRING
,
888 (UINT_PTR
)idMenuTitle
, m_title
.wx_str()) ||
889 !::InsertMenu(hMenu
, 1u, MF_BYPOSITION
, (unsigned)-1, NULL
) )
891 wxLogLastError(wxT("InsertMenu"));
899 // remove the title and the separator after it
900 if ( !RemoveMenu(hMenu
, 0, MF_BYPOSITION
) ||
901 !RemoveMenu(hMenu
, 0, MF_BYPOSITION
) )
903 wxLogLastError(wxT("RemoveMenu"));
910 WinStruct
<MENUITEMINFO
> info
;
911 info
.fMask
= MIIM_TYPE
;
912 info
.fType
= MFT_STRING
;
913 info
.cch
= m_title
.length();
914 info
.dwTypeData
= const_cast<wxChar
*>(m_title
.wx_str());
915 if ( !SetMenuItemInfo(hMenu
, 0, TRUE
, & info
) )
917 wxLogLastError(wxT("SetMenuItemInfo"));
920 if ( !ModifyMenu(hMenu
, 0u,
921 MF_BYPOSITION
| MF_STRING
,
922 (UINT_PTR
)idMenuTitle
, m_title
.wx_str()) )
924 wxLogLastError(wxT("ModifyMenu"));
931 // put the title string in bold face
932 if ( !m_title
.empty() )
934 SetDefaultMenuItem(GetHmenu(), (UINT
)idMenuTitle
);
939 // ---------------------------------------------------------------------------
941 // ---------------------------------------------------------------------------
943 bool wxMenu::MSWCommand(WXUINT
WXUNUSED(param
), WXWORD id_
)
945 const int id
= (signed short)id_
;
947 // ignore commands from the menu title
948 if ( id
!= idMenuTitle
)
950 // Default value for uncheckable items.
953 // update the check item when it's clicked
954 wxMenuItem
* const item
= FindItem(id
);
955 if ( item
&& item
->IsCheckable() )
959 // Get the status of the menu item: note that it has been just changed
960 // by Toggle() above so here we already get the new state of the item.
962 // Also notice that we must pass unsigned id_ and not sign-extended id
963 // to ::GetMenuState() as this is what it expects.
964 UINT menuState
= ::GetMenuState(GetHmenu(), id_
, MF_BYCOMMAND
);
965 checked
= (menuState
& MF_CHECKED
) != 0;
968 SendEvent(id
, checked
);
974 // get the menu with given handle (recursively)
975 #if wxUSE_OWNER_DRAWN
976 wxMenu
* wxMenu::MSWGetMenu(WXHMENU hMenu
)
979 if ( GetHMenu() == hMenu
)
982 // recursively query submenus
983 for ( size_t n
= 0 ; n
< GetMenuItemCount(); ++n
)
985 wxMenuItem
* item
= FindItemByPosition(n
);
986 wxMenu
* submenu
= item
->GetSubMenu();
989 submenu
= submenu
->MSWGetMenu(hMenu
);
998 #endif // wxUSE_OWNER_DRAWN
1000 // ---------------------------------------------------------------------------
1002 // ---------------------------------------------------------------------------
1004 void wxMenuBar::Init()
1006 m_eventHandler
= this;
1008 #if wxUSE_TOOLBAR && defined(__WXWINCE__)
1011 // Not using a combined wxToolBar/wxMenuBar? then use
1012 // a commandbar in WinCE .NET just to implement the
1014 #if defined(WINCE_WITH_COMMANDBAR)
1015 m_commandBar
= NULL
;
1016 m_adornmentsAdded
= false;
1020 wxMenuBar::wxMenuBar()
1025 wxMenuBar::wxMenuBar( long WXUNUSED(style
) )
1030 wxMenuBar::wxMenuBar(size_t count
, wxMenu
*menus
[], const wxString titles
[], long WXUNUSED(style
))
1034 for ( size_t i
= 0; i
< count
; i
++ )
1036 // We just want to store the menu title in the menu itself, not to
1037 // show it as a dummy item in the menu itself as we do with the popup
1038 // menu titles in overridden wxMenu::SetTitle().
1039 menus
[i
]->wxMenuBase::SetTitle(titles
[i
]);
1040 m_menus
.Append(menus
[i
]);
1042 menus
[i
]->Attach(this);
1046 wxMenuBar::~wxMenuBar()
1048 // In Windows CE (not .NET), the menubar is always associated
1049 // with a toolbar, which destroys the menu implicitly.
1050 #if defined(WINCE_WITHOUT_COMMANDBAR) && defined(__POCKETPC__)
1053 wxToolMenuBar
* toolMenuBar
= wxDynamicCast(GetToolBar(), wxToolMenuBar
);
1055 toolMenuBar
->SetMenuBar(NULL
);
1058 // we should free Windows resources only if Windows doesn't do it for us
1059 // which happens if we're attached to a frame
1060 if (m_hMenu
&& !IsAttached())
1062 #if defined(WINCE_WITH_COMMANDBAR)
1063 ::DestroyWindow((HWND
) m_commandBar
);
1064 m_commandBar
= (WXHWND
) NULL
;
1066 ::DestroyMenu((HMENU
)m_hMenu
);
1068 m_hMenu
= (WXHMENU
)NULL
;
1073 // ---------------------------------------------------------------------------
1074 // wxMenuBar helpers
1075 // ---------------------------------------------------------------------------
1077 void wxMenuBar::Refresh()
1082 wxCHECK_RET( IsAttached(), wxT("can't refresh unattached menubar") );
1084 #if defined(WINCE_WITHOUT_COMMANDBAR)
1087 CommandBar_DrawMenuBar((HWND
) GetToolBar()->GetHWND(), 0);
1089 #elif defined(WINCE_WITH_COMMANDBAR)
1091 DrawMenuBar((HWND
) m_commandBar
);
1093 DrawMenuBar(GetHwndOf(GetFrame()));
1097 WXHMENU
wxMenuBar::Create()
1099 // Note: this doesn't work at all on Smartphone,
1100 // since you have to use resources.
1101 // We'll have to find another way to add a menu
1102 // by changing/adding menu items to an existing menu.
1103 #if defined(WINCE_WITHOUT_COMMANDBAR)
1107 wxToolMenuBar
* const bar
= static_cast<wxToolMenuBar
*>(GetToolBar());
1111 HWND hCommandBar
= GetHwndOf(bar
);
1113 // notify comctl32.dll about the version of the headers we use before using
1114 // any other TB_XXX messages
1115 SendMessage(hCommandBar
, TB_BUTTONSTRUCTSIZE
, sizeof(TBBUTTON
), 0);
1118 wxZeroMemory(tbButton
);
1119 tbButton
.iBitmap
= I_IMAGENONE
;
1120 tbButton
.fsState
= TBSTATE_ENABLED
;
1121 tbButton
.fsStyle
= TBSTYLE_DROPDOWN
|
1122 TBSTYLE_NO_DROPDOWN_ARROW
|
1125 for ( unsigned i
= 0; i
< GetMenuCount(); i
++ )
1127 HMENU hPopupMenu
= (HMENU
) GetMenu(i
)->GetHMenu();
1128 tbButton
.dwData
= (DWORD
)hPopupMenu
;
1129 wxString label
= wxStripMenuCodes(GetMenuLabel(i
));
1130 tbButton
.iString
= (int) label
.wx_str();
1132 tbButton
.idCommand
= NewControlId();
1133 if ( !::SendMessage(hCommandBar
, TB_INSERTBUTTON
, i
, (LPARAM
)&tbButton
) )
1135 wxLogLastError(wxT("TB_INSERTBUTTON"));
1139 m_hMenu
= bar
->GetHMenu();
1141 #else // !__WXWINCE__
1145 m_hMenu
= (WXHMENU
)::CreateMenu();
1149 wxLogLastError(wxT("CreateMenu"));
1153 for ( wxMenuList::iterator it
= m_menus
.begin();
1154 it
!= m_menus
.end();
1157 if ( !::AppendMenu((HMENU
)m_hMenu
, MF_POPUP
| MF_STRING
,
1158 (UINT_PTR
)(*it
)->GetHMenu(),
1159 (*it
)->GetTitle().wx_str()) )
1161 wxLogLastError(wxT("AppendMenu"));
1167 #endif // __WXWINCE__/!__WXWINCE__
1170 int wxMenuBar::MSWPositionForWxMenu(wxMenu
*menu
, int wxpos
)
1173 wxASSERT(menu
->GetHMenu());
1176 #if defined(__WXWINCE__)
1177 int totalMSWItems
= GetMenuCount();
1179 int totalMSWItems
= GetMenuItemCount((HMENU
)m_hMenu
);
1182 int i
; // For old C++ compatibility
1183 for(i
=wxpos
; i
<totalMSWItems
; i
++)
1185 if(GetSubMenu((HMENU
)m_hMenu
,i
)==(HMENU
)menu
->GetHMenu())
1188 for(i
=0; i
<wxpos
; i
++)
1190 if(GetSubMenu((HMENU
)m_hMenu
,i
)==(HMENU
)menu
->GetHMenu())
1197 // ---------------------------------------------------------------------------
1198 // wxMenuBar functions to work with the top level submenus
1199 // ---------------------------------------------------------------------------
1201 // NB: we don't support owner drawn top level items for now, if we do these
1202 // functions would have to be changed to use wxMenuItem as well
1204 void wxMenuBar::EnableTop(size_t pos
, bool enable
)
1206 wxCHECK_RET( IsAttached(), wxT("doesn't work with unattached menubars") );
1207 wxCHECK_RET( pos
< GetMenuCount(), wxT("invalid menu index") );
1209 int flag
= enable
? MF_ENABLED
: MF_GRAYED
;
1211 EnableMenuItem((HMENU
)m_hMenu
, MSWPositionForWxMenu(GetMenu(pos
),pos
), MF_BYPOSITION
| flag
);
1216 bool wxMenuBar::IsEnabledTop(size_t pos
) const
1218 wxCHECK_MSG( pos
< GetMenuCount(), false, wxS("invalid menu index") );
1219 WinStruct
<MENUITEMINFO
> mii
;
1220 mii
.fMask
= MIIM_STATE
;
1221 if ( !::GetMenuItemInfo(GetHmenu(), pos
, TRUE
, &mii
) )
1223 wxLogLastError(wxS("GetMenuItemInfo(menubar)"));
1226 return !(mii
.fState
& MFS_GRAYED
);
1229 void wxMenuBar::SetMenuLabel(size_t pos
, const wxString
& label
)
1231 wxCHECK_RET( pos
< GetMenuCount(), wxT("invalid menu index") );
1233 m_menus
[pos
]->wxMenuBase::SetTitle(label
);
1235 if ( !IsAttached() )
1239 //else: have to modify the existing menu
1241 int mswpos
= MSWPositionForWxMenu(GetMenu(pos
),pos
);
1244 UINT flagsOld
= ::GetMenuState((HMENU
)m_hMenu
, mswpos
, MF_BYPOSITION
);
1245 if ( flagsOld
== 0xFFFFFFFF )
1247 wxLogLastError(wxT("GetMenuState"));
1252 if ( flagsOld
& MF_POPUP
)
1254 // HIBYTE contains the number of items in the submenu in this case
1256 id
= (UINT_PTR
)::GetSubMenu((HMENU
)m_hMenu
, mswpos
);
1264 WinStruct
<MENUITEMINFO
> info
;
1265 info
.fMask
= MIIM_TYPE
;
1266 info
.fType
= MFT_STRING
;
1267 info
.cch
= label
.length();
1268 info
.dwTypeData
= const_cast<wxChar
*>(label
.wx_str());
1269 if ( !SetMenuItemInfo(GetHmenu(), id
, TRUE
, &info
) )
1271 wxLogLastError(wxT("SetMenuItemInfo"));
1275 if ( ::ModifyMenu(GetHmenu(), mswpos
, MF_BYPOSITION
| MF_STRING
| flagsOld
,
1276 id
, label
.wx_str()) == (int)0xFFFFFFFF )
1278 wxLogLastError(wxT("ModifyMenu"));
1285 wxString
wxMenuBar::GetMenuLabel(size_t pos
) const
1287 wxCHECK_MSG( pos
< GetMenuCount(), wxEmptyString
,
1288 wxT("invalid menu index in wxMenuBar::GetMenuLabel") );
1290 return m_menus
[pos
]->GetTitle();
1293 // ---------------------------------------------------------------------------
1294 // wxMenuBar construction
1295 // ---------------------------------------------------------------------------
1297 wxMenu
*wxMenuBar::Replace(size_t pos
, wxMenu
*menu
, const wxString
& title
)
1299 wxMenu
*menuOld
= wxMenuBarBase::Replace(pos
, menu
, title
);
1303 menu
->wxMenuBase::SetTitle(title
);
1305 #if defined(WINCE_WITHOUT_COMMANDBAR)
1311 int mswpos
= MSWPositionForWxMenu(menuOld
,pos
);
1313 // can't use ModifyMenu() because it deletes the submenu it replaces
1314 if ( !::RemoveMenu(GetHmenu(), (UINT
)mswpos
, MF_BYPOSITION
) )
1316 wxLogLastError(wxT("RemoveMenu"));
1319 if ( !::InsertMenu(GetHmenu(), (UINT
)mswpos
,
1320 MF_BYPOSITION
| MF_POPUP
| MF_STRING
,
1321 (UINT_PTR
)GetHmenuOf(menu
), title
.wx_str()) )
1323 wxLogLastError(wxT("InsertMenu"));
1327 if ( menuOld
->HasAccels() || menu
->HasAccels() )
1329 // need to rebuild accell table
1330 RebuildAccelTable();
1332 #endif // wxUSE_ACCEL
1341 bool wxMenuBar::Insert(size_t pos
, wxMenu
*menu
, const wxString
& title
)
1343 // Find out which MSW item before which we'll be inserting before
1344 // wxMenuBarBase::Insert is called and GetMenu(pos) is the new menu.
1345 // If IsAttached() is false this won't be used anyway
1347 #if defined(WINCE_WITHOUT_COMMANDBAR)
1353 int mswpos
= (!isAttached
|| (pos
== m_menus
.GetCount()))
1354 ? -1 // append the menu
1355 : MSWPositionForWxMenu(GetMenu(pos
),pos
);
1357 if ( !wxMenuBarBase::Insert(pos
, menu
, title
) )
1360 menu
->wxMenuBase::SetTitle(title
);
1364 #if defined(WINCE_WITHOUT_COMMANDBAR)
1368 memset(&tbButton
, 0, sizeof(TBBUTTON
));
1369 tbButton
.iBitmap
= I_IMAGENONE
;
1370 tbButton
.fsState
= TBSTATE_ENABLED
;
1371 tbButton
.fsStyle
= TBSTYLE_DROPDOWN
| TBSTYLE_NO_DROPDOWN_ARROW
| TBSTYLE_AUTOSIZE
;
1373 HMENU hPopupMenu
= (HMENU
) menu
->GetHMenu() ;
1374 tbButton
.dwData
= (DWORD
)hPopupMenu
;
1375 wxString label
= wxStripMenuCodes(title
);
1376 tbButton
.iString
= (int) label
.wx_str();
1378 tbButton
.idCommand
= NewControlId();
1379 if (!::SendMessage((HWND
) GetToolBar()->GetHWND(), TB_INSERTBUTTON
, pos
, (LPARAM
)&tbButton
))
1381 wxLogLastError(wxT("TB_INSERTBUTTON"));
1384 wxUnusedVar(mswpos
);
1386 if ( !::InsertMenu(GetHmenu(), mswpos
,
1387 MF_BYPOSITION
| MF_POPUP
| MF_STRING
,
1388 (UINT_PTR
)GetHmenuOf(menu
), title
.wx_str()) )
1390 wxLogLastError(wxT("InsertMenu"));
1394 if ( menu
->HasAccels() )
1396 // need to rebuild accell table
1397 RebuildAccelTable();
1399 #endif // wxUSE_ACCEL
1408 bool wxMenuBar::Append(wxMenu
*menu
, const wxString
& title
)
1410 WXHMENU submenu
= menu
? menu
->GetHMenu() : 0;
1411 wxCHECK_MSG( submenu
, false, wxT("can't append invalid menu to menubar") );
1413 if ( !wxMenuBarBase::Append(menu
, title
) )
1416 menu
->wxMenuBase::SetTitle(title
);
1418 #if defined(WINCE_WITHOUT_COMMANDBAR)
1424 #if defined(WINCE_WITHOUT_COMMANDBAR)
1428 memset(&tbButton
, 0, sizeof(TBBUTTON
));
1429 tbButton
.iBitmap
= I_IMAGENONE
;
1430 tbButton
.fsState
= TBSTATE_ENABLED
;
1431 tbButton
.fsStyle
= TBSTYLE_DROPDOWN
| TBSTYLE_NO_DROPDOWN_ARROW
| TBSTYLE_AUTOSIZE
;
1433 size_t pos
= GetMenuCount();
1434 HMENU hPopupMenu
= (HMENU
) menu
->GetHMenu() ;
1435 tbButton
.dwData
= (DWORD
)hPopupMenu
;
1436 wxString label
= wxStripMenuCodes(title
);
1437 tbButton
.iString
= (int) label
.wx_str();
1439 tbButton
.idCommand
= NewControlId();
1440 if (!::SendMessage((HWND
) GetToolBar()->GetHWND(), TB_INSERTBUTTON
, pos
, (LPARAM
)&tbButton
))
1442 wxLogLastError(wxT("TB_INSERTBUTTON"));
1446 if ( !::AppendMenu(GetHmenu(), MF_POPUP
| MF_STRING
,
1447 (UINT_PTR
)submenu
, title
.wx_str()) )
1449 wxLogLastError(wxT("AppendMenu"));
1454 if ( menu
->HasAccels() )
1456 // need to rebuild accelerator table
1457 RebuildAccelTable();
1459 #endif // wxUSE_ACCEL
1468 wxMenu
*wxMenuBar::Remove(size_t pos
)
1470 wxMenu
*menu
= wxMenuBarBase::Remove(pos
);
1474 #if defined(WINCE_WITHOUT_COMMANDBAR)
1480 #if defined(WINCE_WITHOUT_COMMANDBAR)
1483 if (!::SendMessage((HWND
) GetToolBar()->GetHWND(), TB_DELETEBUTTON
, (UINT
) pos
, (LPARAM
) 0))
1485 wxLogLastError(wxT("TB_DELETEBUTTON"));
1489 if ( !::RemoveMenu(GetHmenu(), (UINT
)MSWPositionForWxMenu(menu
,pos
), MF_BYPOSITION
) )
1491 wxLogLastError(wxT("RemoveMenu"));
1496 if ( menu
->HasAccels() )
1498 // need to rebuild accell table
1499 RebuildAccelTable();
1501 #endif // wxUSE_ACCEL
1512 void wxMenuBar::RebuildAccelTable()
1514 // merge the accelerators of all menus into one accel table
1515 size_t nAccelCount
= 0;
1516 size_t i
, count
= GetMenuCount();
1517 wxMenuList::iterator it
;
1518 for ( i
= 0, it
= m_menus
.begin(); i
< count
; i
++, it
++ )
1520 nAccelCount
+= (*it
)->GetAccelCount();
1525 wxAcceleratorEntry
*accelEntries
= new wxAcceleratorEntry
[nAccelCount
];
1528 for ( i
= 0, it
= m_menus
.begin(); i
< count
; i
++, it
++ )
1530 nAccelCount
+= (*it
)->CopyAccels(&accelEntries
[nAccelCount
]);
1533 SetAcceleratorTable(wxAcceleratorTable(nAccelCount
, accelEntries
));
1535 delete [] accelEntries
;
1539 #endif // wxUSE_ACCEL
1541 void wxMenuBar::Attach(wxFrame
*frame
)
1543 wxMenuBarBase::Attach(frame
);
1545 #if defined(WINCE_WITH_COMMANDBAR)
1549 m_commandBar
= (WXHWND
) CommandBar_Create(wxGetInstance(), (HWND
) frame
->GetHWND(), NewControlId());
1554 if (!CommandBar_InsertMenubarEx((HWND
) m_commandBar
, NULL
, (LPTSTR
) m_hMenu
, 0))
1556 wxLogLastError(wxT("CommandBar_InsertMenubarEx"));
1563 RebuildAccelTable();
1564 #endif // wxUSE_ACCEL
1567 #if defined(WINCE_WITH_COMMANDBAR)
1568 bool wxMenuBar::AddAdornments(long style
)
1570 if (m_adornmentsAdded
|| !m_commandBar
)
1573 if (style
& wxCLOSE_BOX
)
1575 if (!CommandBar_AddAdornments((HWND
) m_commandBar
, 0, 0))
1577 wxLogLastError(wxT("CommandBar_AddAdornments"));
1588 void wxMenuBar::Detach()
1590 wxMenuBarBase::Detach();
1593 // get the menu with given handle (recursively)
1594 wxMenu
* wxMenuBar::MSWGetMenu(WXHMENU hMenu
)
1596 wxCHECK_MSG( GetHMenu() != hMenu
, NULL
,
1597 wxT("wxMenuBar::MSWGetMenu(): menu handle is wxMenuBar, not wxMenu") );
1599 #if wxUSE_OWNER_DRAWN
1601 for ( size_t n
= 0 ; n
< GetMenuCount(); ++n
)
1603 wxMenu
* menu
= GetMenu(n
)->MSWGetMenu(hMenu
);
1613 #endif // wxUSE_MENUS