读书人

有关创建组件!解决方案

发布时间: 2012-02-22 19:36:55 作者: rapoo

有关创建组件!
unit Unit1;

interface

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

Type
TcyButton = Class(TButton)
Private
Public
procedure Click(Sender: TObject);
end;

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

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
Panel: TPanel;
Button: TcyButton;
begin
Panel := TPanel.Create(Nil);
Panel.Parent := Form1;

with Panel do
begin
Button := TcyButton.Create(Nil);
With Button do
begin
Parent := Panel;
OnClick := Click;
end;
end;
end;

{ Button }

procedure TcyButton.Click(Sender: TObject);
begin
Showmessage( 'a '); //ShowMessage 是没有问题的
Close; //Close 没有办法做, cyButton不知道应该Close谁啊? ^_^ 这儿应该怎么写?
end;

end.


[解决办法]
Button := TcyButton.Create(self
);
TForm(Parent).Close;
就可以了
------解决方案--------------------


楼上的做法违背了楼主的意思,楼主是希望把按钮创建在panel上,而不是窗口上。
根据楼主的情况,你是直接将创建代码和布局代码混在一起。没有独立开来。那么你就没有必要这么麻烦,因为代码本身已经失去了可可重用性,在click事件中直接Form1.close 就可以了
如果真的不想这样,你也可以嵌套来完成搜索Form的目的
在click事件中这样写
var
P:TwinControl;
begin
while P.Parent <> nil do
begin
P:=P.Parent;
if P.Parent=nil then
Break;
end;
TForm(P).Close;
end;

读书人网 >.NET

热点推荐