我想知道DWScript是否支持使用脚本方法作为Delphi上控件的事件处理程序。例如,我希望将TButton OnClick事件链接到脚本中存在的方法。
我可以通过调用返回TMethod对象的GetProcMethod来使用RemObjects Delphi脚本引擎完成此操作。然后,我使用SetMethodProp将脚本方法分配给按钮的OnClick事件。
procedure LinkMethod(SourceMethodName: String; Instance: TObject; ScriptMethodName: String);
var
ScriptMethod: TMethod;
begin
ScriptMethod := ScriptEngine.GetProcMethod(ScripMethodName);
SetMethodProp(Instance, SourceMethodName, ScriptMethod);
end;我想在DWScript中做这件事,而不是使用Rem objects脚本引擎,因为它可以做一些我需要的东西。
发布于 2012-10-30 12:03:17
我决定转而使用RemObjects。它是最容易使用的,而且能做我需要的事情。
发布于 2012-10-02 22:21:45
AFAIK DWScript并不直接支持你想要实现的功能,但它可以以不同的方式实现。我将尝试发布一些如何实现它的源代码,但您可能需要根据您的需要对其进行调整。
首先,声明一个小的包装器类,每个脚本方法应该分开:
type
TDwsMethod = class
private
FDoExecute: TNotifyEvent;
FScriptText: string;
FDws: TDelphiWebScript;
FLastResult: string;
FMethod: TMethod;
protected
procedure Execute(Sender: TObject);
public
constructor Create(const AScriptText: string); virtual;
destructor Destroy; override;
property Method: TMethod read FMethod;
property LastResult: string read FLastResult;
published
property DoExecute: TNotifyEvent read FDoExecute write FDoExecute;
end;
constructor TDwsMethod.Create(const AScriptText: string);
begin
inherited Create();
FDoExecute := Execute;
FScriptText := AScriptText;
FDws := TDelphiWebScript.Create(nil);
FMethod := GetMethodProp(Self, 'DoExecute');
end;
destructor TDwsMethod.Destroy;
begin
FDws.Free;
inherited Destroy;
end;
procedure TDwsMethod.Execute(Sender: TObject);
begin
ShowMessage('My Method executed. Value: ' + FDws.Compile(FScriptText).Execute().Result.ToString);
end;现在,我们必须在代码中的某个地方创建该类的实例(例如,在窗体的create事件中):
procedure TMainForm.FormCreate(Sender: TObject);
begin
FDWSMethod := TDwsMethod.Create('PrintLn(100);'); //in constructor we pass script text which needs to be executed
//now we can set form's mainclick event to our DWS method
SetMethodProp(Self, 'MainClick', FDWSMethod.Method);
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FDWSMethod.Free;
end;现在,当我们调用MainClick时,我们的脚本被编译并执行:

https://stackoverflow.com/questions/12549625
复制相似问题