c++ 如何以编程方式显示功能区按钮的下拉菜单?

8e2ybdfx  于 2023-08-09  发布在  其他
关注(0)|答案(2)|浏览(173)

我有一个子项目添加了一套功能区按钮。当用户点击按钮下面的小箭头时,这些项目就会显示出来。我想显示这样的下拉菜单时,按钮本身被点击。我怎么能这么做呢?
我最初的想法是在用户单击按钮时以编程方式显示菜单。我已经能够在工具栏(here)上做同样的事情,但在Ribbon上使用类似的解决方案会创建无限递归:

// ...
ON_COMMAND(ID_RIBBON_BUTTON, &MainFrame::OnButtonClicked)
// ...

CMFCRibbonPanel *panel = /* initialization */
CMFCRibbonButton *button = new CMFCRibbonButton(ID_RIBBON_BUTTON, "Caption");
panel->Add(button);

CMFCRibbonButton *item1 = new CMFCRibbonButton(ID_RIBBON_BUTTON, "Item 1");
button->AddSubItem(item1);
CMFCRibbonButton *item2 = new CMFCRibbonButton(ID_RIBBON_BUTTON, "Item 2");
button->AddSubItem(item2);

// ...
void MainFrame::OnButtonClicked()
{
  if (auto button = static_cast<CMFCRibbonButton *>(m_ribbons.wndRibbonBar.FindByID(ID_RIBBON_BUTTON))) {

    // button->OnClick({}); // <- causes infinite recursion

    // What to do here?
  }
}

字符串

dauxcl2d

dauxcl2d1#

到目前为止,我发现的最简单的方法是使用受保护的方法CMFCRibbonButton::OnShowPopupMenu。这意味着派生CMFCRibbonButton类并更改方法的可见性:

#include <afxribbonbutton.h>

class CMyMFCRibbonButton : public CMFCRibbonButton {
public:
  using CMFCRibbonButton::CMFCRibbonButton;

  virtual void OnShowPopupMenu() override {
    CMFCRibbonButton::OnShowPopupMenu();
  }
};

// ...
ON_COMMAND(ID_RIBBON_BUTTON, &MainFrame::OnButtonClicked)
// ...

CMFCRibbonPanel *panel = /* initialization */
CMyMFCRibbonButton *button = new CMyMFCRibbonButton(ID_RIBBON_BUTTON, "Caption");
panel->Add(button);

CMFCRibbonButton *item1 = new CMFCRibbonButton(ID_RIBBON_BUTTON, "Item 1");
button->AddSubItem(item1);
CMFCRibbonButton *item2 = new CMFCRibbonButton(ID_RIBBON_BUTTON, "Item 2");
button->AddSubItem(item2);

// ...
void MainFrame::OnButtonClicked()
{
  if (auto button = static_cast<CMyMFCRibbonButton*>(m_ribbons.wndRibbonBar.FindByID(ID_RIBBON_BUTTON))) {
    button->OnShowPopupMenu();
  }
}

字符串

k2fxgqgv

k2fxgqgv2#

如果创建一个空白弹出子菜单并附加到按钮,则按钮将按您的请求工作,同时显示以前作为子项添加的按钮。

CMenu map_menu;
map_menu.CreateMenu();

button->SetHMenu(map_menu.GetSafeHmenu());

字符串

相关问题