2009-12-13 19 views
3

當我從單元創建一個動態組件時,我無法創建OnClick事件。 當我製作一個動態組件單元2我無法訪問OnClick事件。多個單元的Delphi OnClick問題

unit Unit1 
type 
    TForm1 = class(TForm) 
     procedure FormCreate(Sender: TObject); 
    private 
     { Private declarations } 
    public 
     Procedure ClickBtn1(Sender: TObject); 
    end; 

var 
    Form1: TForm1; 
    MyBtn1: TButton; 
implementation 

{$R *.dfm} 

{ TForm1 } 
uses Unit2; 

procedure TForm1.ClickBtn1; 
begin 
    MyBtn1.Caption := 'OK'; 
    MakeBtn2; 
end; 


procedure TForm1.FormCreate(Sender: TObject); 
begin 
    MyBtn1 := TButton.Create(Self); 
    MyBtn1.Parent := Form1; 
    MyBtn1.Name := 'Btn1'; 
    MyBtn1.Left := 50; 
    MyBtn1.Top := 100; 
    MyBtn1.Caption := 'Click Me'; 
    MyBtn1.OnClick := ClickBtn1; 
end; 


end. 



unit Unit2; 

interface 

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

procedure MakeBtn2; 
procedure ClickBtn2;  
var 
    MyBtn2: TButton; 

implementation 

Uses Unit1; 

procedure MakeBtn2; 
begin 
    MyBtn2 := TButton.Create(Form1); 
    MyBtn2.Parent := Form1; 
    MyBtn2.Name := 'Btn2'; 
    MyBtn2.Left := 250; 
    MyBtn2.Top := 100; 
    MyBtn2.Caption := 'Click Me'; 
    MyBtn2.OnClick := ClickBtn2; //Compiler ERROR 
end; 

procedure ClickBtn2; 
begin 
    MyBtn1.Caption := 'OK'; 
end; 
end. 

回答

1

您確定第一個示例有效嗎?這些都不應該編譯。

一個onClick處理程序是一個TNotifyEvent,其被定義爲

procedure(Sender: TObject) of object; 

這意味着,它必須是一個對象(例如一個形式)的方法,並且該方法簽名必須是一個程序這需要一個TObject參數。您的過程MakeBtn2不是對象方法,它們都不需要發件人:TObject。

+0

什麼將acheive我想要的東西的最佳方式? – 2009-12-13 14:13:24

+0

使用正確的簽名在表單上聲明一個方法,並將您要執行的代碼放在那裏。 – 2009-12-13 14:28:21

2

看一看這篇文章「Creating A Component at Runtime

報價:

我想在代碼中創建一個按鈕,把 它在窗體上並附加一個過程來 其click事件。如何從代碼中獲取鏈接到預定義的 過程名稱的 點擊事件?我假設 在對象瀏覽器中的IDE鏈接是 這個答案的關鍵,但我想在運行時做 ,而不是在開發中。

首先,您可以將任何 對象的方法指定爲 ,因爲它具有相同的形式。看看 下面的代碼:

{This method is from another button that when pressed will create 
the new button.} 
procedure TForm1.Button1Click(Sender: TObject); 
var 
    btnRunTime : TButton; 
begin 
    btnRunTime := TButton.Create(form1); 
    with btnRunTime do begin 
    Visible := true; 
    Top := 64; 
    Left := 200; 
    Width := 75; 
    Caption := 'Press Me'; 
    Name := 'MyNewButton'; 
    Parent := Form1; 
    OnClick := ClickMe; 
    end; 
end; 

{This is the method that gets assigned to the new button's OnClick method} 
procedure TForm1.ClickMe(Sender : TObject); 
begin 
    with (Sender as TButton) do 
    ShowMessage('You clicked me'); 
end; 

正如你所看到的,我創建了一個名爲ClickMe新方法 ,這是宣佈 Form1的私有部分:

type 
    TForm1 = class(TForm 
    ... 
    ... 
    private 
    procedure ClickMe(Sender : TObject); 
    published 
    end; 

有關其他示例和解釋,請參閱以下內容: