星期四, 11月 24, 2011

設定元件位置在點擊按鈕的正上方

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses Unit2;

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  point1: TPoint;
begin
  point1:=Button1.Parent.ClientToScreen(Button1.BoundsRect.TopLeft);
  point1:=ClientToScreen(point1);
  caption := 'X:'+IntToStr(point1.x)+' '+
    'Y:'+IntToStr(point1.y);
  Form2:= TForm2.Create(self);
  try
    Form2.SetPosition(point1.x, point1.y); //x右邊到元件 y上邊到元件
    Form2.ShowModal;
  finally
    Form2.Free;
  end;
end;

end.
unit Unit2;

interface

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

type
  TForm2 = class(TForm)
  private
    { Private declarations }
  public
    { Public declarations }
    procedure SetPosition(x, y: Integer);
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

procedure TForm2.SetPosition(x, y: Integer);
begin
  self.left:=x-(self.Width div 2);
  self.Top:=y-self.Height;
end;

end.