23W
23W

Reputation: 1540

How to change button position in CMFCToolBar?

Can I change position of some button in CMFCToolBar ? For example set third button at begin of toolbar.

Upvotes: 1

Views: 884

Answers (2)

23W
23W

Reputation: 1540

My version for few buttons:

// pIDs - array of buttons IDs
// nIDCounts - size of array
void ArrangeButtons(CMFCToolBar& wnd, const UINT* pIDs, UINT nIDCounts) 
{

    std::vector<std::unique_ptr<CMFCToolBarButton>> aBtns;
    std::transform(pIDs, std::next(pIDs, nIDCounts), std::inserter(aBtns, std::end(aBtns)), [&](UINT nID)-> std::unique_ptr < CMFCToolBarButton > {
            std::unique_ptr<CMFCToolBarButton> res;
            CMFCToolBarButton* pBtn = wnd.GetButton(wnd.CommandToIndex(nID));
            if ((pBtn != nullptr) && pBtn->IsKindOf(RUNTIME_CLASS(CMFCToolBarButton))) {
                    res.reset(STATIC_DOWNCAST(CMFCToolBarButton, pBtn->GetRuntimeClass()->CreateObject()));
                    res->CopyFrom(*pBtn);
            }
            return std::move(res);
    });

    wnd.RemoveAllButtons();
    std::for_each(std::begin(aBtns), std::end(aBtns), [&](std::unique_ptr<CMFCToolBarButton>& btn) {
            if (btn) {
                    wnd.InsertButton(*btn);
            }
    });
}

Upvotes: 0

xMRi
xMRi

Reputation: 15375

Just get the old button, insert it at the new position, delete the old one.

// Get button at position 3 and move it to position 1
auto *pButton = bar.Getbutton(2);
bar.InsertButton(*pButton,0);
bar.RemoveButton(2);

It is save to dereference the pointer because InsertButton creates a copy.

Upvotes: 2

Related Questions