您的位置:首页 > 其它

自定义CEdit右键菜单,并响应右键菜单命令

2010-06-02 16:41 295 查看
首先创建一个类,这里命名为CEditBox,其派生自CEdit。然后在资源中创建一个Menu,我这里命名其ID为IDR_VOL_VALUE。

在CEditBox的OnContextMenu中添加自定义右键菜单:

void CEditBox::OnContextMenu(CWnd* pWnd, CPoint point)
{
if (point.x == -1 && point.y == -1)		//SHIFT+F10
{
//keystroke invocation
CRect rect;
GetClientRect(rect);
ClientToScreen(rect);

point = rect.TopLeft();
point.Offset(5, 5);
}

CMenu menu;
VERIFY(menu.LoadMenu(IDR_VOL_VALUE));

CMenu* pPopup = menu.GetSubMenu(0);
ASSERT(pPopup != NULL);

CTestView *pView = (CTestView*)(GetParent());
pView->m_pCurEdit = this;

pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
pView);
}


我在CTestView中使用了CEditBox类,CTestView派生自CFormView,右键菜单命令也是在CTestView中进行响应。这里有个问题,由于我在CTestView中使用了不止一个CEditBox控件,我们在命令消息中要知道是在哪个CEditBox上面点击了右键。我采取如下措施:

1、在CTestView中定义了一个CEditBox指针
CEditBox *m_pCurEdit;


m_pCurEdit用来保存我们的命令响应函数是针对的哪个控件。

2、在在CEditBox的OnContextMenu中,TrackPopupMenu之前得到其父窗口的指针pView,然后把this指针赋给pView->m_pCurEdit。代码如下:

CTestView *pView = (CTestView*)(GetParent());
pView->m_pCurEdit = this;


3、消息响应函数在CEditBox的父窗口即CTestView中实现,代码如下:

//电压等幅值
void CTestView::OnVolEqual()
{
// TODO: Add your command handler code here
CString str;

if(m_pCurEdit == &m_valueUa)
{
m_valueUa.GetWindowText(str);
m_valueUb.SetWindowText(str);
m_valueUc.SetWindowText(str);
m_valueUz.SetWindowText(str);
}
if(m_pCurEdit == &m_valueUb)
{
m_valueUb.GetWindowText(str);
m_valueUa.SetWindowText(str);
m_valueUc.SetWindowText(str);
m_valueUz.SetWindowText(str);
}
if(m_pCurEdit == &m_valueUc)
{
m_valueUc.GetWindowText(str);
m_valueUa.SetWindowText(str);
m_valueUb.SetWindowText(str);
m_valueUz.SetWindowText(str);
}
if(m_pCurEdit == &m_valueUz)
{
m_valueUz.GetWindowText(str);
m_valueUa.SetWindowText(str);
m_valueUb.SetWindowText(str);
m_valueUc.SetWindowText(str);
}

m_pCurEdit = NULL;
}

//额定相电压
void CTestView::OnVolRating()
{
// TODO: Add your command handler code here
if(m_pCurEdit == NULL)
return;
m_pCurEdit->SetWindowText("100.0");
}

//电压零
void CTestView::OnVolZero()
{
// TODO: Add your command handler code here
if(m_pCurEdit == NULL)
return;
m_pCurEdit->SetWindowText("0.0");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: