Wednesday, October 20, 2010

Modify the pasting text of edit control in the clipboard

The steps are:
1. Inherit CEdit. For example CMyEdit

2. Handle WM_PASTE message
BEGIN_MESSAGE_MAP(CMyEdit, CEdit)
ON_MESSAGE(WM_PASTE, OnEditPaste)
END_MESSAGE_MAP()

3. OnEditPaste() method
- Open the clip board
- Read the clip board text
- Modify the text
- Write the text in the clip board

LRESULT CMyEdit::OnEditPaste(WPARAM /*wParam*/, LPARAM /*lParam*/)
{
#ifdef UNICODE
UINT nFlag = CF_UNICODETEXT;
#else
UINT nFlag = CF_TEXT;
#endif

if(!IsClipboardFormatAvailable(nFlag))
return 1;

if(!OpenClipboard())
return 1;

HGLOBAL hData = GetClipboardData(nFlag);
if(hData != NULL)
{
CString strText;
LPTSTR lptstr = (LPTSTR)GlobalLock(hData);
if(lptstr != NULL)
{
strText = lptstr;
// Modify the text
}
GlobalUnlock(hData);

EmptyClipboard();

HGLOBAL buff = GlobalAlloc(GMEM_DDESHARE, (strText.GetLength() + 1) * sizeof(TCHAR));
if(buff != NULL)
{
lptstr = (LPTSTR)GlobalLock(buff);
_tcscpy(lptstr, strText.GetBuffer());
strText.ReleaseBuffer();
GlobalUnlock(buff);
SetClipboardData(nFlag, buff);
}

}
CloseClipboard();

Default();

return 1;
}