一. 重写控件的GetDragImages方法.
实现步骤:1.重写控件的GetDragImages方法
class TMyPanel:public TPanel{
private:
TDragImageList*dragimgs;
protected:
virtual TDragImageList* __fastcall GetDragImages(void)
{
Graphics::TBitmap*bmp=new Graphics::TBitmap();
bmp->Width=Width;
bmp->Height=Height;
PaintTo(bmp->Canvas->Handle,0,0);
dragimgs->Width=Width;
dragimgs->Height=Height;
dragimgs->Add(bmp,NULL);
return dragimgs;
}
public:
__fastcall TMyPanel(TComponent*AOwner)
:TPanel(AOwner){
Width=300;Height=200;
DragMode=dmAutomatic;//设置自动拖放
ControlStyle<< csDisplayDragImage;
dragimgs=NULL;
Font->Color=clRed;
Caption=\"Hello This is a test of Control Drag\";
dragimgs=new TDragImageList(this);
}
2.对使用该控件的窗体添加以下方法,并在窗体建立时调用FixCSStyle(this)使窗体里的所有控件都可以显示拖放图形
void FixCSStyle(TComponent*fc)//使所有控件都可以显示拖放图形
{ for(int i=0;i<fc->ComponentCount;i++)
{
TComponent*c=fc->Components[i];
if(c->InheritsFrom(__classid(TControl)))
((TControl*)c)->ControlStyle<< csDisplayDragImage;
if(c->ComponentCount>0)FixCSStyle(c);
}
};
方法二.不重写控件,使用TDragControlObject的派生类实现.本人以文本对象的拖放为例
步骤:1.实现TDragControlObject的派生类
class TTextDragObject:public TDragControlObject
{
private:
TDragImageList*dragImgs;
AnsiString FDragText;
protected:
virtual TDragImageList* __fastcall GetDragImages(void){
if(dragImgs==NULL)
dragImgs=new TDragImageList(NULL);
Graphics::TBitmap*bmp=new Graphics::TBitmap();bmp->Height=bmp->Canvas-.TextHeight(FDragText);bmp->Width=bmp->Canvas->TextWidth(FDragText);
bmp->Canvas->TextOut(0,0,FDragText);
dragImgs->Width=bmp->Width;
dragImgs->Height=bmp->Height;
int idx=dragImgs->AddMasked(bmp,clWhite);
dragImgs->SetDragImage(idx,0,0);
};
public:
__fastcall TTextDragObject(TControl*AControl,AnsiString text);
__fastcall virtual ~TTextDragObject(void);
__property AnsiString DragText={read=FDragText,write=FDragText};
};
2.在拖放源控件的OnStartDrag事件中加上如下一句
void __fastcall TForm1::Panel1StartDrag(TObject *Sender,
TDragObject *&DragObject)
{
DragObject=new TTextDragObject(Panel1,\"Drag Text test\");
}