delphi 鼠标拖拽panel
时间: 2023-09-05 11:06:46 浏览: 112
在 Delphi 中实现鼠标拖拽 Panel 的方法如下:
1. 在鼠标按下事件中获取鼠标位置和 Panel 的位置
```
procedure TForm1.PanelMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := True;
FMousePos := Point(X, Y);
FPanelPos := Panel1.Left;
end;
```
2. 在鼠标移动事件中更新 Panel 的位置
```
procedure TForm1.PanelMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if FDragging then
Panel1.Left := FPanelPos + (X - FMousePos.X);
end;
```
3. 在鼠标释放事件中停止拖拽
```
procedure TForm1.PanelMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
end;
```
完整代码如下:
```
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 PanelMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PanelMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure PanelMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
FDragging: Boolean;
FMousePos: TPoint;
FPanelPos: Integer;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.PanelMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := True;
FMousePos := Point(X, Y);
FPanelPos := Panel1.Left;
end;
procedure TForm1.PanelMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if FDragging then
Panel1.Left := FPanelPos + (X - FMousePos.X);
end;
procedure TForm1.PanelMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FDragging := False;
end;
end.
```
阅读全文