如何从表单单元外部访问delphi控件? [英] How can I access a delphi control from outside the form's unit?
问题描述
我试图从这样定义的过程中调用Timer的Enabled属性: procedure Slide(Form:TForm; Show:Boolean);
而不是固定的表单名称(例如: Form2.Timer ...
)
I'm trying to call the Enabled property of a Timer from a procedure defined like this: procedure Slide(Form: TForm; Show: Boolean);
and not with a fixed form name (like: Form2.Timer...
)
将表单的单位放入使用后列表,这行得通: Form2.Timer1.Enabled:= True;
但以下项不起作用: Form.Timer1.Enabled: = True;
(其中Form是作为参数传递给过程的表单。
After putting the form's unit in the uses list, this works: Form2.Timer1.Enabled := True;
but the following is not working: Form.Timer1.Enabled := True;
(where Form is the form passed as parameter to the procedure.
如何访问表单上的Timer组件?
How to get access to the Timer component on my form?
预先感谢。
推荐答案
您不能从以下位置访问计时器您的过程,因为您的参数是TForm,并且TForm没有Timer1成员。您必须像这样调整过程:
You cannot access the Timer from your procedure because your parameter is a TForm, and TForm does not have a Timer1 member. You have to adjust your procedure like this:
uses
Unit2; //unit with your form
procedure Slide(Form: TForm2; Show: Boolean); //change TForm2 to the classname you use
begin
Form.Timer1.Enabled := True;
end;
编辑:
如果要传递任何形式,可以尝试以下操作:
If you want to pass any form, you can try this:
procedure Slide(Form: TForm; const aTimerName: string; Show: Boolean);
var
lComponent: TComponent;
begin
lComponent := Form.FindComponent(aTimerName);
if Assigned(lComponent) and (lComponent is TTimer) then
TTimer(lComponent).Enabled := True;
end;
通过表单上的按钮调用:
Call like this from a button on your form:
procedure TForm2.Button1Click(Sender: TObject);
begin
Slide(Self, 'Timer1', False);
end;
或者您可以让Form继承一个带有打开计时器方法的接口。不过,这有点复杂。
Or you let your Form inherit an interface with methods to turn on the timer. It's a little bit more complicated though.
这篇关于如何从表单单元外部访问delphi控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!