代码改变世界

添加右键菜单

2014-11-25 00:49  sylar_liang  阅读(300)  评论(0编辑  收藏  举报

有2种方式添加右键菜单:

1.无需在资源中添加Menu

(1) 在.h中定义HMenu变量,在.cpp中初始化菜单项。

HMenu m_hMenu; // .h中定义
m_hMenu = CreatePopupMenu(); // InitDialog中初始化
MENUITEMINFO mi;
mi.cbsize = sizeof(mi);
mi.fMask = MIIM_ID | MIIM_STRING;
mi.fType = MFT_STRING;
mi.fState = MFS_ENABLED; // 使能. MFS_DISABLED(不使能)

mi_wID = 1;
mi_dwTypeData = _T("Select All");
InsertMenuItem(m_hMenu,0,TRUE,&mi);

mi_wID = 2;
mi_dwTypeData = _T("Clear");
InsertMenuItem(m_hMenu,1,TRUE,&mi);

(2) 重载右键按下消息 OnRButtonDown

ClientToScreen(&point); // 转换为屏幕坐标
OnContextMenu(this,point);

(3) 重载OnContextMenu函数

mi.cbSize = sizeof(mi);
mi.fMask = MIIM_STATE;
mi.fState = MFS_ENABLED;
SetMenuItemInfo(m_hMenu,2,FALSE,&mi); //  2表示位置

// 此处必须为TPM_RETURNCMD,可以返回0,1,2,3...否则只返回0,1的值
INT cmdID = (INT)TrackPopupMenu(m_hMenu,TPM_RETURNCMD,point.x,point.y,0,this->m_hWnd,NULL);
switch(cmdID)
{
    case 1: // select all
        OnEditSelectAll(); // 响应函数
        break;
    case 2: // copy
        this->copy();
        break;
    default:
        break;
}

 

2.在资源文件中添加菜单资源

(1)资源文件中添加弹出菜单资源

(2)添加对应菜单项的响应函数

(3)重载OnContextMenu函数

CMenu menu;
menu.LoadMenu(IDR_POPUPMENU); // IDR_POPUPMENU为自定义的弹出菜单ID
CMenu *popMenu = menu.GetSubMenu(0);
popMenu->EnableMenuItem(ID_EDIT,MF_BYCOMMAND | MF_DISABLE | MF_GRAYED); // 使这一菜单项变灰,失效
popMenu->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON,point.x,point.y,this);

// 假如坐标不对,可以重载右键按下,调用ClientToScreen,再调用OnContextMenu