1.任務(wù):在窗體中隨意移動(dòng)某個(gè)控件课竣,本例子選用的是個(gè)Shape控件挟鸠,且不能移出窗體炭懊;
2.打開(kāi)IDE,新建VCL應(yīng)用务冕,添加一個(gè)Shape1控件拇囊,添加一個(gè)RichEdit1控件;
- 需要手動(dòng)設(shè)置的屬性:Shape1.Shape 為'stCircle'覆享;
4.需要手動(dòng)添加的事件:
(1)窗體的創(chuàng)建事件:onCreate佳遂;
(2)Shape1的鼠標(biāo)操作事件:MouseDown、MouseMove撒顿、MouseUp;
5.編寫代碼:
var
c: boolean; // 是否移動(dòng)的開(kāi)關(guān)
tx, ty: Integer; // 鼠標(biāo)在控件上按下時(shí)的坐標(biāo)
procedure TForm1.FormCreate(Sender: TObject);
begin
c := false; // 窗體啟動(dòng)時(shí)丑罪,設(shè)置控件不可移動(dòng)
end;
// 下面是控件的鼠標(biāo)按下事件
procedure TForm1.Shape1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then //判斷按下的是不是鼠標(biāo)左鍵
begin
c := true; // 按下鼠標(biāo)左鍵后,可以移動(dòng)
RichEdit1.SelAttributes.Color := clBlue; // 改變最下一行的字體顏色
RichEdit1.Lines.Add('開(kāi)始坐標(biāo):Left:' + Shape1.Left.ToString + '--Top:' +
Shape1.Top.ToString);
tx := X; // 記錄下鼠標(biāo)點(diǎn)擊的開(kāi)始坐標(biāo)X
ty := Y; // 記錄下鼠標(biāo)點(diǎn)擊的開(kāi)始坐標(biāo) Y
end;
end;
// 下面是控件的鼠標(biāo)移動(dòng)事件
procedure TForm1.Shape1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
if c then
begin
Shape1.Left := Shape1.Left + X - tx; // 改變控件的Left坐標(biāo) ,X-tx是相對(duì)開(kāi)始時(shí)移動(dòng)的距離
Shape1.Top := Shape1.Top + Y - ty; // 改變控件的Top坐標(biāo) ,Y-ty是相對(duì)開(kāi)始時(shí)移動(dòng)的距離
// Form1.ClientWidth是窗體的用戶區(qū)的大小凤壁,即除去邊框的大小吩屹,控件在這個(gè)范圍內(nèi)是可見(jiàn)的。
if Shape1.Left >= Form1.ClientWidth - Shape1.Width then // 如果移動(dòng)到右邊界了
Shape1.Left := Form1.ClientWidth - Shape1.Width // 讓控件緊靠右邊界
else if Shape1.Left <= 0 then // 如果移動(dòng)到左邊界
Shape1.Left := 0; // 讓控件緊靠左邊界
if Shape1.Top >= Form1.ClientHeight - Shape1.Height then // 如果移動(dòng)到下邊界了
Shape1.Top := Form1.ClientHeight - Shape1.Height // 讓控件緊靠下邊界
else if Shape1.Top <= 0 then // 如果移動(dòng)到上邊界了
Shape1.Top := 0; // 讓控件緊靠上邊界
RichEdit1.Lines.Add('移動(dòng)坐標(biāo):Left:' + Shape1.Left.ToString + '--Top:' +
Shape1.Top.ToString);
end;
end;
// 下面是控件的鼠標(biāo)釋放事件
procedure TForm1.Shape1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
c := false; // 放開(kāi)鼠標(biāo)后拧抖,不可以移動(dòng)
RichEdit1.SelAttributes.Color := clRed; // 改變最下一行的字體顏色
RichEdit1.Lines.Add('終點(diǎn)坐標(biāo):Left:' + Shape1.Left.ToString + '--Top:' +
Shape1.Top.ToString);
end;
示例圖片:
14.1.jpg
14.2.jpg
14.3.jpg
14.4.jpg
14.5.jpg
14.6.jpg
14.7.jpg