Myaction:=TAction.Create(aowner);
Myaction.Name:='aHookPlay';
这样的代码如果实现时在同一个Form上你是绝对不可以放两个这样的组件的。
因为Myaction的拥有者是当前的Form,而同一个组件不能用用两个同名的子组件。所以行不通。
方案一:
Myaction:=TAction.Create(Self);
Myaction.Name:='aHookPlay';
方案二:用计数器来解决,MyAction大家共用。
unit glMyAction;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, ActnList;
type
gltest = class(TComponent)
private
MyAction: TAction;
FParent: TComponent;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
end;
procedure Register;
implementation
uses glMyAction;
var
CompCount : Integer; //定义一个计数器
procedure Register;
begin
RegisterComponents('SelfControl', [gltest]);
end;
{ gltest }
constructor gltest.Create(AOwner: TComponent);
begin
inherited;
fparent := AOwner;
// if csDesigning in self.ComponentState then
// begin
Myaction :=fparent.FindComponent('aHookPlay');//如果Myaction存在了就直接指过去
if Myaction= nil then
begin
Myaction := TAction.Create(aowner);
{1}{这个参数一定要用Aowner,如果用Self就没问题了,但那不是我要的结果}
Myaction.Name := 'aHookPlay';
{2}{Name一定要赋值!}
end;
Inc(CompCount);//计数器加一
Myaction.Caption := '结束播音';
// end;
end;
destructor gltest.Destroy;
begin
Dec(CompCount);//计数器减一
if CompCount = 0 then //等与0也就是没有人用了,才释放掉
MyAction.Free;
inherited Destroy;
end;
initialization
CompCount := 0;
end.