制作可移動(dòng)的窗體的MovePanel控件
發(fā)表時(shí)間:2023-07-30 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]使用Winamp是有個(gè)EasyMove的功能,也就是不在標(biāo)題欄上拖動(dòng)鼠標(biāo)就能移動(dòng)窗體,雖然EasyMove功能很好實(shí)現(xiàn),可還不如做個(gè)控件一勞永逸,另外這個(gè)控件還有一個(gè)更有用的功能,呆會(huì)兒就能見到。我...
使用Winamp是有個(gè)EasyMove的功能,也就是不在標(biāo)題欄上拖動(dòng)鼠標(biāo)就能移動(dòng)窗體,雖然EasyMove功能很好實(shí)現(xiàn),可還不如做個(gè)控件一勞永逸,另外這個(gè)控件還有一個(gè)更有用的功能,呆會(huì)兒就能見到。我們先看看如何實(shí)現(xiàn)它吧!
---- 建立一個(gè)空的Unit,把以下代碼Copy進(jìn)去,再把它添加到Delphi的控件庫(kù)里,這樣MovePanel控件就做好了。
unit MovePanel;
interface
uses
Windows, Classes, Controls,ExtCtrls;
type
TMovePanel = class(TPanel) //這個(gè)控件是繼承Tpanel類的
private
PrePoint:TPoint;
Down:Boolean;
{ Private declarations }
protected
{ Protected declarations }
public
constructor Create(AOwner:TComponent);
override;
//重載鼠標(biāo)事件,搶先處理消息
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;
//如果方法已存在,就觸發(fā)相應(yīng)事件去調(diào)用它,
若不加此語句會(huì)造成訪存異常
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.
接下來,看看怎么用它吧。
----用法一:拖一個(gè)Form下來,加上我們的MovePanel,Align屬性設(shè)為alClient,運(yùn)行一下,移動(dòng)窗體的效果還不錯(cuò)吧!想取消此功能,把MovePanel的Enabled屬性設(shè)為False即可,簡(jiǎn)單吧!
----用法二:拖一個(gè)Form下來,加上普通的Panel,調(diào)整好大小,再在Panel上加上我們的MovePanel, Align屬性設(shè)為alClient,運(yùn)行一下,這一次在我們拖動(dòng)MovePanel時(shí)不是窗體在移動(dòng),而是Panel和MovePanel一起在窗體上移動(dòng),如果我們?cè)侔哑渌目丶旁贛ovePanel上,就成了可以在窗體上任意移動(dòng)的控件了,就這么簡(jiǎn)單!