프로그래밍 노트

델파이에서 동적으로 컨트롤 만드는 두가지 방법 본문

델파이

델파이에서 동적으로 컨트롤 만드는 두가지 방법

띠리 2007. 10. 22. 20:14

델파이에서 동적으로 컨트롤 만드는 두가지 방법

밑의 소스의 ①과 ②를 보면 컨트롤을 동적으로 만드는 법이 두가지가 있다.
①처럼 바로 컨트롤을 만드는 방법과
②처럼 기존에 동적 배열 컨트롤을 정의해 두고
배열의 크기를 설정해서 컨트롤을 만드는 방법이 있다.

이 프로그램을 실행시켜서 컨트롤 키를 누르고 마우스를 클릭하거나
컨트롤 키를 누르지 않고 마우스를 클릭하면 동적으로 컨트롤들이 폼에 생성되어진다.

그리고 그렇게 생성되어진 컨트롤을 클릭하면 각 컨트롤의 캡션이 폼의 캡션에 표시되어진다.

unit Unit2;

interface

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

type
  TForm2 = class(TForm)
    procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
  private
    procedure GetCtrlName(Sender: TObject);
  public

    btnD : Array of TButton;

  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

var
  Count1 :integer = 1;
  Count2 :integer = 1;
  sParent : string;

// 컨트롤 키를 눌렀는지 알려줌
function CtrlDown : Boolean;
var
  State : TKeyboardState;
begin
  GetKeyboardState(State);
  Result := ((State[vk_Control] And 128) <> 0);
end;

procedure TForm2.FormMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  if Button = mbRight then Exit;


  // 컨트롤 키를 눌렀을때
  if CtrlDown then
  begin

    // 버튼을 동적으로 생성①
    with TButton.Create(Self) do begin
      Parent := Self;
      Height := 30;
      Width := width + Count1*2;
      Left := X - Width div 2;
      Top := Y - Height div 2;
      Name := Format('D1Button%d',[Count1]);
      Caption := 'OOO' + IntToStr(Count1);
      OnClick := GetCtrlName;
    end;

    Inc(Count1);

  end
  // 컨트롤 키를 안눌렀을때
  else
  begin

    SetLength(btnD, Count2);

    // 버튼을 동적 배열로 생성②
    btnD[Count2] := TButton.Create(nil);
    with btnD[Count2] do
    begin
      Parent := Self;
      Height := 30;
      Width := width + Count1*2;
      Left := X - Width div 2;
      Top := Y - Height div 2;
      Caption := 'XXX' + IntToStr(Count1);
      Name := Format('D2Button%d',[Count1]);
      OnClick := GetCtrlName;
    end;

   Inc(Count2);

  end;


end;

// 동적으로 만들어진 컨트롤을 클릭했을 때 실행
procedure TForm2.GetCtrlName(Sender: TObject);
begin
  Form2.Caption  := (Sender as TButton).Caption;
  //Form2.Caption  := (Sender as TButton).name;

  if ((Sender as TButton).Left + (Sender as TButton).Width + 50) > Form2.Width  then
    (Sender as TButton).Left := 0
  else
    (Sender as TButton).Left :=  (Sender as TButton).Left + 50;
end;

end.



invalid-file

BDS 2006

소스 파일
Comments