It is uncommon here to post links to sources. It is better to post only relevant parts. In your case this would be the code to prepare the drag text and get it upon dropping. However, I had a look on your files:
- [UPDATE]: You forgot to call
AfxOleInit()
from within InitInstance()
. - You are passing the text strings without terminating
NULL
character. - You are using
GlobalSize()
to determine the string length on the drop side. That may lead to unexpected results because the allocated global memory size may be larger than the requested size. - You are using
CSharedFile
objects to create global memory objects and CMemFile
objects to acccess drop objects. While this is not wrong it is not necessary. - Optional: Don't call the default handler in
CDragEdit::OnLButtonDown()
when performing drag (all following mouse events are handled by OLE so that the control will not receive a button up message) - Optional:
CDragEdit::OnLButtonDown()
needs some more checks: Start drag only when control has focus and clicked on selected text.
Here is a short code snippet showing how drag and drop can be done:
DROPEFFECT DragText(LPCTSTR lpszText, DROPEFFECT dwEffect)
{
size_t nSize = (_tcslen(lpszText) + 1) * sizeof(TCHAR);
HGLOBAL hGlobal = ::GlobalAlloc(GMEM_MOVEABLE, static_cast<SIZE_T>(nSize));
LPTSTR lpDst = static_cast<LPTSTR>(::GlobalLock(hGlobal));
::CopyMemory(lpDst, lpszText, nSize);
::GlobalUnlock(hGlobal);
COleDataSource Data;
#ifdef _UNICODE
Data.CacheGlobalData(CF_UNICODETEXT, hGlobal);
#else
Data.CacheGlobalData(CF_TEXT, hGlobal);
#endif
return Data.DoDragDrop(dwEffect);
}
void GetDropText(CString& str, COleDataObject* pDataObject)
{
str = _T("");
if (pDataObject->IsDataAvailable(CF_UNICODETEXT))
{
HGLOBAL hGlobal = pDataObject->GetGlobalData(CF_UNICODETEXT);
LPCWSTR lpSrc = static_cast<LPCWSTR>(::GlobalLock(hGlobal));
str = lpSrc;
::GlobalUnlock(hGlobal);
}
else if (pDataObject->IsDataAvailable(CF_TEXT))
{
HGLOBAL hGlobal = pDataObject->GetGlobalData(CF_TEXT);
LPCSTR lpSrc = static_cast<LPCSTR>(::GlobalLock(hGlobal));
str = lpSrc;
::GlobalUnlock(hGlobal);
}
}