使用Winamp是有個EasyMove的功能,也就是不在標題欄上拖動鼠標就能移動窗體,雖然EasyMove功能很好實現,可還不如做個控件一勞永逸,另外這個控件還有一個更有用的功能,呆會兒就能見到。我們先看看如何實現它吧!
---- 建立一個空的Unit,把以下代碼Copy進去,再把它添加到Delphi的控件庫里,這樣MovePanel控件就做好了。
unit MovePanel; interface uses Windows, Classes, Controls,ExtCtrls; type TMovePanel = class(TPanel) //這個控件是繼承Tpanel類的 private PrePoint:TPoint; Down:Boolean; { Private declarations } protected { Protected declarations } public constructor Create(AOwner:TComponent); override; //重載鼠標事件,搶先處理消息 procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);override; procedure MouseMove(Shift: TShiftState; X, Y: Integer);override; { Public declarations } published { Published declarations } end;
procedure Register;
implementation
constructor TMovePanel.Create(AOwner:TComponent); begin inherited Create(AOwner); //繼承父類的Create方法 end;
procedure TMovePanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button=MBLeft) then begin Down:=true; GetCursorPos(PrePoint); end; //如果方法已存在,就觸發相應事件去調用它, 若不加此語句會造成訪存異常 if assigned(OnMouseDown) then OnMouseDown(self,Button,shift,x,y); end;
procedure TMovePanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (Button=MBLeft) and Down then Down:=False; if assigned(OnMouseUp) then OnMouseUp(Self,Button,shift,X,y); end;
procedure TMovePanel.MouseMove(Shift: TShiftState; X, Y: Integer); Var NowPoint:TPoint; begin if down then begin GetCursorPos(nowPoint); //self.Parent在Form中就是MovePanel所在的窗體, 或是MovePanel所在的容器像Panel self.Parent.Left:=self.Parent.left +NowPoint.x-PrePoint.x; self.parent.Top:=self.Parent.Top +NowPoint.y-PrePoint.y; PrePoint:=NowPoint; end; if Assigned(OnMouseMove) then OnMouseMove(self,Shift,X,y); end;
procedure Register; begin RegisterComponents('Md3', [TMovePanel]); end;
end.
接下來,看看怎么用它吧。 ----用法一:拖一個Form下來,加上我們的MovePanel,Align屬性設為alClient,運行一下,移動窗體的效果還不錯吧!想取消此功能,把MovePanel的Enabled屬性設為False即可,簡單吧!
----用法二:拖一個Form下來,加上普通的Panel,調整好大小,再在Panel上加上我們的MovePanel, Align屬性設為alClient,運行一下,這一次在我們拖動MovePanel時不是窗體在移動,而是Panel和MovePanel一起在窗體上移動,如果我們再把其他的控件放在MovePanel上,就成了可以在窗體上任意移動的控件了,就這么簡單!
|