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:
- Get a pointer to the frame window hosting the toolbar.
- Get a pointer to the toolbar control.
- [optional] Get the button index for a specific command ID.
- Get a pointer to the button at the specified index.
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.