按住panel 拖動窗體的方法

del88發表於2024-06-09

有些時候,我們的窗體沒有 頂部欄,比如:窗體的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.

效果如下:
image

相關文章