有些时候,我们的窗体没有 顶部栏,比如:窗体的borderstyle = bsNone; 我们想在顶部放置一个panel,来拖动窗体,方法如下,直接上代码了:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls;
type
TForm1 = class(TForm)
Panel1: TPanel;
procedure Panel1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Panel1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Panel1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
/// <summary>
/// 鼠标左键是否按下了
/// </summary>
leftDown: Boolean;
/// <summary>
/// 鼠标左键按下时,鼠标的位置
/// </summary>
oldX: Integer;
oldY: Integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Panel1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
leftDown := True;
oldX := x;
oldY := y;
end;
end;
procedure TForm1.Panel1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if leftDown then
begin
Left := Left + (x - oldX);
Top := Top + (y - oldY);
end;
end;
procedure TForm1.Panel1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
leftDown := False;
end;
end.
效果如下: