Search code examples
mfccontextmenucricheditctrl

MFC: How do you implement a context menu for CRichEditView in a CTabView tab?


I have a CTabView with one of the tabs a CRichEditView. Rich text is added to the control and shows fine. If I select text within the CRichEditView the toolbar edit items work fine (for example, copy highlights, and if I click on it, it copies to the clipboard). However, I found that if I selected text and right click there is no context menu with a CRichEditView like there was with CEditView. Searching the Internet, I found an implementation for CRichEditView::GetContextMenu() to try and use. It first had an assert failure because the CDocument is not a rich text type, so for testing, I removed it (commented out below) and ended up with the following:

HMENU CMyRichView::GetContextMenu(WORD seltyp, LPOLEOBJECT lpoleobj, CHARRANGE* lpchrg)
{
  // TODO: Add your specialized code here and/or call the base class
  /*
  CRichEditCntrItem* pItem = GetSelectedItem();
    if (pItem == NULL || !pItem->IsInPlaceActive())*/
    {
      CMenu menuText;
      menuText.LoadMenu(IDR_CONTEXT_EDIT_MENU);
      CMenu* pMenuPopup = menuText.GetSubMenu(0);
      menuText.RemoveMenu(0, MF_BYPOSITION);
      return pMenuPopup->Detach();
    }
}

Where the IDR_CONTEXT_EDIT_MENU is:

IDR_CONTEXT_EDIT_MENU MENU
BEGIN
    POPUP "edit"
    BEGIN
        MENUITEM "&Copy\tCtrl+C",               ID_EDIT_COPY
    END
END

Now when I right-click I see the context menu. However, when I choose "copy", nothing happens. So I mapped the ID_EDIT_COPY so I could set a break point to see if it was called.

void CMyRichView::OnEditCopy()
{
  // TODO: Add your command handler code here
    ASSERT_VALID(this);
    GetRichEditCtrl().Copy();
}

It's not if the context item is used, but it is if the toolbar is used.

What am I missing and doing wrong?

TIA!!


Solution

  • If the message goes to CTabView then add CTabView::OnEditCopy handler.

    Otherwise, you can override PreTranslateMessage as shown below, this will make sure the message is sent to CMyRichEditView::OnEditCopy.

    BOOL CMyRichEditView::PreTranslateMessage(MSG *msg)
    {
        if(msg->message == WM_CONTEXTMENU || msg->message == WM_RBUTTONDOWN)
        {
            CMenu menu;
            menu.LoadMenu(IDR_CONTEXT_EDIT_MENU);
            int c = menu.GetMenuItemCount();
            CMenu* popup = menu.GetSubMenu(0);
            popup->TrackPopupMenu(0, msg->pt.x, msg->pt.y, this, NULL);
            return TRUE;
        }
        return CRichEditView::PreTranslateMessage(msg);
    }