Delphi的窗体编程技巧──用鼠标拖动无标题窗口

编程的时候,有时为了需要,会将窗体的BorderStyle设置为bsNone,即无标题窗体。但是这样一来,因为没有了标题栏,就无法拖动窗体了。其实,我们只需要用以下的方法,就可以实现平滑拖动窗体了。
   在OnMouseDown事件中加入
   OldX:=x;

OldY:=u;

在OnMouseMove事件中加入
   Form1.Left:=Form1.Left+x-Oldx;

Form1.Top:=Form1.Top+y-Oldy;

#1 源代码如下:
   unit Unit1;

interface
   uses
   Windows, Messages,SysUtils, Classes,Graphics,Controls,Forms, Dialogs;

type
   TForm1 = class(TForm)
   procedure FormMouseDown(Sender:TObject;Button:TMouseButton;

Shift:TShiftState;X,Y,Integer);

procedure FormMouseMove(Sender:TObject;Button:TMouseButton;

Shift:TShiftState;X,Y,Integer);

private
  
{Private declarations}

public
  
{Private declarations}

end;

var
   Form1:TForm1;

OldX,OldY:integer; //定义全局变量
   implementation
  
{$R *.DFM}

procedure TForm1.FormMouseDown(Sender:TObject;Button:TMouseButton;
   Shift:TShiftState;X,Y:Integer);
   begin
   OldX:=x;

OldY:=y;

end;

procedure TForm1.FormMouseMove(Sender:TObject;Button:TMouseButton

Shift:TShiftState;X,,
   Y:Integer);

begin
   if ssleft in shift then //按下鼠标左键
   begin
   Form1.Left:=Form1.Left+x-Oldx;

Form1.Top:=Form1.Top+y-Oldy;

end;

end;

end.
   注:以上代码在Delphi5.0、Win98 SE中测试通过。