I have a color button on toolbar, it was created in CMainFrame, how can I get a pointer to the color button which is CMFCColorMenuButton derived class from View, like the code below(part of MSOffice2007Demo Sample)? :
CMFCRibbonBar* pRibbon = ((CMainFrame*) GetTopLevelFrame())->GetRibbonBar();
ASSERT_VALID(pRibbon);
CMFCRibbonColorButton* pFontColorBtn = DYNAMIC_DOWNCAST(CMFCRibbonColorButton, pRibbon->FindByID(ID_FONT_COLOR));
The process to access button controls in a toolbar requires a number of steps to navigate to the control in question. The following list illustrates this:
Convert the base class button type to derived class.
// Get pointer to mainframe window
CMainFrame* pFrameWnd = DYNAMIC_DOWNCAST( CMainFrame, AfxGetMainWnd() );
// Get pointer to the toolbar
CBasePane* pPane = pFrameWnd->GetPane( AFX_IDW_TOOLBAR );
CMFCToolBar* pToolBar = DYNAMIC_DOWNCAST( CMFCToolBar, pPane );
// Find button index for command ID
int index = pToolBar->CommandToIndex( ID_COLOR_PICKER );
// Retrieve button
CMFCToolBarButton* pButton = pToolBar->GetButton( index );
// Convert button to appropriate type
CMFCColorMenuButton* pColorButton = DYNAMIC_DOWNCAST( CMFCColorMenuButton,
pButton );
A few notes on the implementation:
Error handling has been omitted for brevity. Whenever there is a DYNAMIC_DOWNCAST
the return value can be NULL
and has to be checked. Likewise, the call to CommandToIndex
can fail and requires error handling.
DYNAMIC_DOWNCAST
is similar to a C++ dynamic_cast
in that it evaluates whether a runtime type can be converted to another type. While not all Windows control relationships can be modeled as a C++ class hierarchy, MFC provides its own conversion tool: DYNAMIC_DOWNCAST
.
The ID passed to the call to CommandToIndex
is the command ID assigned to the CMFCColorMenuButton
either through a resource script or at runtime, depending on how the control is created.