我正在使用德尔福7.我已经写了一些代码来创建按钮在运行时(我需要在每个窗体上完全相同的位置上的许多完全相同的按钮,这就是为什么我决定这么做)。但是我在程序中引用它们时遇到了困难(确切地说,OnClick)。我想要单击按钮时打开另一个表单。德尔福 - 在运行时创建的问题引用对象
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, jpeg, ExtCtrls;
procedure buttons(a: TForm);
type
TForm2 = class(TForm)
Image1: TImage;
procedure FormShow(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2; Button1, Button2, Button3, Button4: TButton;
implementation
uses Unit3, Unit4;
{$R *.dfm}
procedure buttons(a: TForm);
begin
Button1 := TButton.Create(a);
Button1.Name := 'Button1';
Button1.Left := 712;
Button1.Top := 96;
Button1.Width := 81;
Button1.Height := 41;
Button1.Visible := True;
Button1.Parent := a;
Button1.Enabled := False;
Button1.Caption := 'Go forwards';
Button2 := TButton.Create(a);
Button2.Name := 'Button2';
Button2.Left := 800;
Button2.Top := 152;
Button2.Width := 81;
Button2.Height := 41;
Button2.Visible := True;
Button2.Parent := a;
Button2.Enabled := False;
Button2.Caption := 'Go right';
Button3 := TButton.Create(a);
Button3.Name := 'Button3';
Button3.Left := 624;
Button3.Top := 152;
Button3.Width := 81;
Button3.Height := 41;
Button3.Visible := True;
Button3.Parent := a;
Button3.Enabled := False;
Button3.Caption := 'Go left';
Button4 := TButton.Create(a);
Button4.Name := 'Button4';
Button4.Left := 712;
Button4.Top := 208;
Button4.Width := 81;
Button4.Height := 41;
Button4.Visible := True;
Button4.Parent := a;
Button4.Enabled := False;
Button4.Caption := 'Go back';
end;
procedure TForm2.FormShow(Sender: TObject);
begin
buttons(Form2);
Button1.Enabled := True;
Button2.Enabled := True;
end;
procedure TForm2.Button1Click(Sender: TObject);
begin
Form3.Show;
Form2.Hide;
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
Form4.Show;
Form2.Hide;
end;
end.
我已经在'type'中声明了OnClicks,因为我可能应该这样做。该程序运行,但创建的按钮不起作用,但可点击。想法?
P.S .:我知道我可以编写更简洁的代码来创建所有这些按钮,但我没有时间思考它,而且这非常重要。我知道这可能很难阅读 - 所有你需要知道的是,我在每个按钮上设置了相同的属性 - 你只需要看Button1,其他的都是一样的。
P.P.S .:不是这个dup问题:Delphi - Referencing Components created at Runtime。我找不到解决我那个问题的方法。
'Button1:= TButton.Create(Button1);'应该读取'Button1:= TButton.Create(a);'。 –
谢谢,它应该。它没有改变,但 - 按钮仍然不起作用。 – Valikojan