Disable / enable ribbon buttons for MFC Feature Pack

I use the MFC Feature Pack, and I have some buttons on the ribbon bar, instances of CMFCRibbonButton. The problem is that I would like to enable and disable some of them under certain conditions, but at runtime. How can i do this? because there is no specific method for this ... I heard that the solution would be to attach / disable event handlers at runtime, but I don't know how ...

+4
source share
2 answers

When you create the CMFCRibbonButton object, you must specify the appropriate command identifier (see the documentation for the CMFCRibbonButton constructor here ). Turning ribbon buttons on and off is performed using the usual command update mechanism in MFC using the CCmdUI class.

For example, if you have a ribbon button with the command identifier ID_MYCOMMAND and you want to process this command in the application view class, you must add these functions to the class:

 // MyView.h class CMyView : public CView { // ... private: afx_msg void OnMyCommand(); afx_msg void OnUpdateMyCommand(CCmdUI* pCmdUI); DECLARE_MESSAGE_MAP() }; 

and implement them in a .cpp file:

 // MyView.cpp void CMyView::OnMyCommand() { // add command handler code. } void CMyView::OnUpdateMyCommand(CCmdUI* pCmdUI) { BOOL enable = ...; // set flag to enable or disable the command. pCmdUI->Enable(enable); } 

You must also add the ON_COMMAND and ON_UPDATE_COMMAND_UI to the message map for the CMyView class:

 // MyView.cpp BEGIN_MESSAGE_MAP(CMyView, CView) ON_COMMAND(ID_MYCOMMAND, &CMyView::OnMyCommand) ON_UPDATE_COMMAND_UI(ID_MYCOMMAND, &CMyView::OnUpdateMyCommand) END_MESSAGE_MAP() 

For more information about message cards in MFC, see TN006: Message Cards on MSDN.

Hope this helps!

+13
source

ChrisN gave a pretty fine answer. You can see an example of how this is done by downloading the sample VS2008 sample from here and opening the MSOffice2007Demo solution.

When you run the sample, check the "Thumbnails" checkbox on the "View" tab on the ribbon; it is disabled.

This is controlled by CMSOffice2007DemoView::OnUpdateViewThumb , which calls pCmdUI->Enable(FALSE); . You can change this to call TRUE or FALSE at run time to enable / disable the button accordingly.

+2
source

All Articles