2016-08-01 90 views
1

我想在MFC單文檔界面(SDI)項目上繪製自定義彈出菜單。

here,我發現The framework calls this member function for the owner of an owner-draw button control, combo-box control, list-box control, or menu when a visual aspect of the control or menu has changed.

所以我加了手柄OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)並添加這個功能裏面的一些代碼,但我發現,這個回調並未由框架調用,當我右鍵單擊視圖,像這樣:
enter image description here
如何動態地創建一個彈出菜單?如何動態地在MFC SDI上繪製自定義菜單

這是我如何得到我的彈出菜單:

void Cdynamic_menu_sdiView::OnContextMenu(CWnd* /* pWnd */, CPoint point) 
{ 
    if (IDR_MY_MENU == 0) 
     return; 
    CMenu dynamicMenu, proxyMenu; 
    if (dynamicMenu.GetSafeHmenu()) 
     dynamicMenu.DestroyMenu(); 
    // Create a new popup menu. 
    if (dynamicMenu.CreatePopupMenu() == FALSE) 
     return; 

    if (proxyMenu.LoadMenu(IDR_MY_MENU) == FALSE) 
     return; 

    int nSubMenu = 1; 
    CMenu* pProxyMenu = proxyMenu.GetSubMenu(nSubMenu); 

    build_dynamic_menu(m_map_menu_element_2, pProxyMenu, dynamicMenu, CString("")); 
    //m_menu_on_draw = &dynamicMenu; // link up the dynamic menu to the on draw menu, so that we can print it on the screen 

    CPoint ptCurPos; // current cursor position 
    GetCursorPos(&ptCurPos); 
    dynamicMenu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, ptCurPos.x, ptCurPos.y, AfxGetMainWnd(), NULL); 
} 

功能build_dynamic_menu()裏面,它是一種深度優先搜索功能,我做InsertMenu(i, MF_BYPOSITION | MF_POPUP | MF_OWNERDRAW, uSubMenuID, strLabel);,這樣我可以動態改變彈出菜單的文本。
既然把這個功能放在這裏太長了,我只能說明這個想法。
我也想動態地改變文本顏色和背景顏色,所以我試圖找到一種方法來通過代碼繪製菜單。

我應該從哪裏開始? owner drawn menus對我有好處嗎?

+1

它是一個自繪菜單嗎?否則,該函數將不會被調用。 – immibis

+0

謝謝,@immibis,我會試着看看這第一個'http:// www.codeproject.com/Articles/7073/How-to-create-owner-drawn-menus-Step-by-Step' – sflee

+1

它doesn與'OnDrawItem'沒有任何關係。顯示你如何加載彈出菜單。 –

回答

0

您已經加載菜單proxyMenu和選定的子菜單pProxyMenu。接下來,打開子菜單pProxyMenu->TrackPopupMenu(而不是proxyMenu->TrackPopupMenu)。如果變量名稱不那麼相似,這將有所幫助。

下面的代碼應該是你所需要的。也沒有必要,如果你根據TrackPopupMenu documentation已經TPM_RIGHTBUTTONnSubMenu = 0;

CMenu proxyMenu; 
if (proxyMenu.LoadMenu(IDR_MY_MENU) == FALSE) 
    return; 

int nSubMenu = 1; 
CMenu* pProxyMenu = proxyMenu.GetSubMenu(nSubMenu); 

CPoint ptCurPos; 
GetCursorPos(&ptCurPos); 
pProxyMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, ptCurPos.x, ptCurPos.y, 
    AfxGetMainWnd()); 

TPM_LEFTBUTTON嘗試:

TPM_RIGHTBUTTON
用戶可以選擇同時與左 ,右鼠標按鈕的菜單項。

另請參閱InsertMenu。使用MF_POPUP添加子菜單,如果這是自繪菜單,則使用MF_OWNERDRAW

+0

由於我想根據不同的情況編輯菜單內的文本,因此我添加了一個'build_dynamic_menu'函數,它具有'dynamicMenu.InsertMenu(i,MF_BYPOSITION | MF_POPUP | MF_OWNERDRAW,uSubMenuID,「My dynamic string」); – sflee

+0

然後使用MF_BYPOSITION並修改彈出菜單。似乎我不知道你的問題是什麼,我試圖猜測... –

+0

我已經使用過'InsertMenu(我,MF_BYPOSITION | MF_POPUP | MF_OWNERDRAW,uSubMenuID,「我的動態字符串」);'是你的意思嗎? – sflee