Disable/Enable Ribbon Buttons for MFC Feature Pack
Asked Answered
J

2

5

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

Jahdol answered 2/2, 2009 at 9:13 Comment(0)
P
16

When you create the CMFCRibbonButton object you have to specify the associated command ID (see the documentation for the CMFCRibbonButton constructor here). Enabling and disabling of ribbon buttons is then done using the usual command update mechanism in MFC, using the CCmdUI class.

For example, if you have a ribbon button whose command ID is ID_MYCOMMAND and you want to handle this command in your application's view class, you should 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 the .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 should also add ON_COMMAND and ON_UPDATE_COMMAND_UI entries 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 on message maps in MFC, refer to TN006: Message Maps in MSDN.

I hope this helps!

Panchito answered 2/2, 2009 at 17:48 Comment(0)
A
2

ChrisN gave a pretty perfect answer. You can see an example of exactly how this is done by downloading the VS2008 Sample Pack from here, and opening the MSOffice2007Demo solution.

When running the sample, look at the "Thumbnails" checkbox in the View tab of the ribbon, it's disabled.

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

Abreaction answered 2/2, 2009 at 23:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.