WinApi,ATL创建上下文菜单功能处理程序

时间:2012-10-01 13:10:51

标签: winapi visual-c++ mfc atl

下面的代码创建了一个窗口,实现了一个CListViewCtrl,并尝试使用3个选项创建一个上下文菜单:new,edit&删除。

class CGuiView : public CWindowImpl<CGuiView, CListViewCtrl>
{
    HMENU hPopupMenu;
    MENUINFO m_ContextMenuInfo;

public:
    DECLARE_WND_CLASS(NULL)

    BOOL PreTranslateMessage(MSG* pMsg)
    {
        pMsg;
        return FALSE;
    }

    BEGIN_MSG_MAP(CGuiView)
        MESSAGE_HANDLER(WM_PAINT, OnPaint)
    //  MESSAGE_HANDLER(WM_LBUTTONUP,)
         MSG_WM_CONTEXTMENU(OnContextMenu) 
         COMMAND_ID_HANDLER(ID_CTXMENU_NEW, OnNewTask)
    END_MSG_MAP()


    LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
    {
        CPaintDC dc(m_hWnd);

        //TODO: Add your drawing code here

        return 0;
    }
     void OnContextMenu ( HWND hwndCtrl, CPoint ptClick )
    {


        hPopupMenu = CreatePopupMenu();

        InsertMenu(hPopupMenu,  0, MF_BYCOMMAND | MF_STRING, ID_CTXMENU_DELETE, TEXT("Delete"));
        InsertMenu(hPopupMenu, ID_CTXMENU_DELETE, MF_BYCOMMAND | MF_STRING, ID_CTXMENU_EDIT, TEXT("Edit"));
        InsertMenu(hPopupMenu, ID_CTXMENU_EDIT, MF_BYCOMMAND | MF_STRING | MF_ENABLED, ID_CTXMENU_NEW , TEXT("New"));

        TrackPopupMenu(hPopupMenu, TPM_TOPALIGN | TPM_LEFTALIGN, ptClick.x, ptClick.y, 0,GetParent(), NULL); 


    }

    LRESULT OnNewTask(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
    {

        CAboutDlg dlg;
        dlg.DoModal();
        return 0;
    }

};

问题是,当我单击我在OnContextMenu函数中创建的New菜单项时,上面的代码不会进入OnNewTask。我做错了什么?

1 个答案:

答案 0 :(得分:2)

您提供GetParent()作为TrackPopupMenu API函数的参数。因此WM_COMMAND被发送到列表视图父级,而不是列表视图本身。

将它发送到列表视图,或将命令从父视图转发到列表视图。您还可以使用Spy ++工具检查调试过程中的消息,以查看确切的发送内容和位置。