从lisrtrl中拖一个图片对象到编辑区域,用到了OLE拖拽。
用OLE对象前在APP的InitInstance()中完成com组建的初始化和OLE初始化,
CoInitialize(NULL);
AfxOleInit();
CoUninitialize(); 在ExitInstance中关闭com,
创建一个新类继承于 COleDropTarget
class CDropTarget : public COleDropTarget
{
DECLARE_DYNAMIC(CDropTarget)
public:
CDropTarget();
virtual ~CDropTarget();
virtual DROPEFFECT OnDragEnter( CWnd* pWnd, COleDataObject* pDataObject, DWORD dwKeyState, CPoint point );
virtual DROPEFFECT OnDragOver( CWnd* pWnd, COleDataObject* pDataObject, DWORD dwKeyState, CPoint point );
virtual void OnDragLeave( CWnd* pWnd );
virtual BOOL OnDrop(CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point);
virtual DROPEFFECT OnDropEx(CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropEffect, DROPEFFECT dropEffectList, CPoint point);
CImageList* CreateDragImageEx(LPPOINT lpPoint, CString csImagePath);
protected:
DECLARE_MESSAGE_MAP()
};
BOOL CDropTarget::OnDrop(CWnd* pWnd, COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point)
{
if(pWnd->IsKindOf(RUNTIME_CLASS(CMyEditView)))//这里需要CMyEditView这个类声明中有DECLARE_DYNAMIC(CMyEditView),
//cpp中有IMPLEMENT_DYNAMIC(CMyEditView, CWnd)
{
return ((CMyEditView*)pWnd)->OnDrop(pWnd, pDataObject, dropEffect, point);
}
else
return COleDropTarget::OnDrop(pWnd, pDataObject, dropEffect, point);
}
创建随鼠标移动的缩略图
CImageList* CDropTarget::CreateDragImageEx(LPPOINT lpPoint, CString csImagePath)
{
Bitmap bmp(csImagePath);
if (Ok != bmp.GetLastStatus()) return NULL;
int nResWidth = bmp.GetWidth();
int nResHeight = bmp.GetHeight();
int nDestWidth = 0;
int nDestHeight = 0;
if(nResWidth >= nResHeight)
{
nDestWidth = nResWidth>80? 80:nResWidth;//缩略图的宽高可以自定义
float fRate = (float)nDestWidth / (float)nResWidth;
nDestHeight = (int)((float)nResHeight * fRate);
}
else
{
nDestHeight = nResHeight>80 ? 80:nResHeight;
float fRate = (float)nDestHeight / (float)nResHeight;
nDestWidth = (int)((float)nResWidth * fRate);
}
Bitmap *pBitmap1 = (Bitmap*)bmp.GetThumbnailImage(nDestWidth, nDestHeight, NULL, NULL);
HBITMAP hBitmap=NULL;
Color color(0,0,0,0);
pBitmap1->GetHBITMAP(color, &hBitmap);
CBitmap bitmap;
bitmap.Attach(hBitmap);
int nBmpW = pBitmap1->GetWidth();
int nBmpH = pBitmap1->GetHeight();
CImageList* pCompleteImageList = new CImageList;
pCompleteImageList->Create(nBmpW, nBmpH, ILC_COLOR24|ILC_MASK, 0, 1);
pCompleteImageList->Add(&bitmap, RGB(0,0,0));
if (lpPoint)
{
lpPoint->x = nBmpW/2;
lpPoint->y = nBmpH/2;
}
SAFE_DELETE(pBitmap1);
bitmap.DeleteObject();
SAFE_DELETE(BG);
return pCompleteImageList;
}