您的位置:首页 > 运维架构

给EditCtrl添加自定义菜单并实现Copy,Cut和Paste功能

2011-04-22 20:23 507 查看
首先自定义一个类CEditCtrl,该类继承与CEdit。在类中添加OnContextMenu(CWnd*, CPoint);

void CEdit::OnContextMenu(CWnd*, CPoint)
{
CMenu Menu;
Menu.LoadMenu(IDR_MENU_CONTEXT); // IDR_MENU_CONTEXT是自定义的菜单的ID
CMenu* pMenu = Menu.GetSubMenu( 0 );
CPoint Pos;
GetCursorPos(&Pos);
pMenu->TrackPopupMenu(TPM_LEFTALIGN|TPM_LEFTBUTTON, Pos.x, Pos.y);
}
 

 

 在以上函数中的IDR_MENU_CONTEXT Menu中添加Copy,Cut和Paste项ID分别为ID_MENU_COPY, ID_MENU_CUT和ID_MENU_PASTE。

   在CEdtiCtrl中添加这几个菜单项的响应函数

 

void CEditCtrl::OnMenuCopy()
{
CString sText;
GetWindowText(sText);
int nSelStart =0, nSelEnd = 0;
GetSel(nSelStart, nSelEnd);
std :: string sDest = sText;
sDest = sDest.substr(nSelStart, nSelEnd-nSelStart);
if ( OpenClipboard() )
{
HGLOBAL ClipBuffer;
char* pBuf;
EmptyClipboard();
Clipbuffer = GlobalAlloc(GMEM_DDESHARE, sText.GetLength()+1);
pBuf  = (char*)GlobalLock(ClipBuffer):
strcpy(pBuf, sDest.c_str()):
GlobalUnlock(ClipBuffer);
SetClipboardData(CF_TEXT, ClipBuffer);
CloseClipboard();
}
}
 

void CEditCtrl::OnMenuPaste()
{
CString sText;
GetWindowText(sText);
int nSelStart =0, nSelEnd = 0;
GetSel(nSelStart, nSelEnd);
std :: string sDest = sText;
std :: string sFront = sDest.substr(0, nSelStart);
std :: string sBack = sDest.substr(nSelEnd, sDest.size());
char* pBuf = NULL;
if ( OpenClipboard() )
{
HGLOBAL ClipBuffer;
ClipBuffer = GetClipboardData(CF_TEXT);
pBuf  = (char*)GlobalLock(ClipBuffer):
GlobalUnlock(ClipBuffer);
CloseClipboard();
}
if ( pBuf )
{
sDest.clear();
sDest += sFront;
sDest += pBuf;
sDest += sBack;
SetWindowText(sDest.c_str());
}
SetSel((int)sDest.size(), –1);               // 光标移到文字最后边。
}
void CEditCtrl::OnMenuCut()
{
CString sText;
GetWindowText(sText);
int nSelStart =0, nSelEnd = 0;
GetSel(nSelStart, nSelEnd);
std :: string sSel = sText;
sDest = sDest.substr(nSelStart, nSelEnd-nSelStart);
if ( OpenClipboard() )
{
HGLOBAL ClipBuffer;
char* pBuf;
EmptyClipboard();
Clipbuffer = GlobalAlloc(GMEM_DDESHARE, sText.GetLength()+1);
pBuf  = (char*)GlobalLock(ClipBuffer):
strcpy(pBuf, sSel.c_str()):
GlobalUnlock(ClipBuffer);
SetClipboardData(CF_TEXT, ClipBuffer);
CloseClipboard();
std :: string sTmp = sText;
std :: string sFront = sTmp.substr(0, nSelStart);
std :: string sBack = sTmp.substr(nSelEnd, sTmp.size()):
std :: string sDest;
sDest += sTmp;
sDest += sBack;
SetWindowText(sDest.c_str());
}
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string menu null
相关文章推荐