使用ScriptControl令程序增加脚本功能

来源:互联网 发布:机智的监狱生活 知乎 编辑:程序博客网 时间:2024/06/10 00:56

1. 导入Microsoft ScriptControl到ActiveX
2. 实现一个自定义的对象IMyObject(Unit2)
3. 使用(Unit1),可用使用下面的脚本:

    MyObject.ShowMsg("MyObject hello");
    Count = 1000;
    AddCount();
    ShowMsg("Count=" + Count);

    IE.Navigate("http://www.google.com");




unit Unit2;

{$WARN SYMBOL_PLATFORM OFF}

interface

uses
  ComObj, ActiveX, ScriptTest_TLB, StdVcl, Dialogs;

type
  TMyObject = class(TAutoObject, IMyObject)
  protected
    FCount: Integer;
    function ShowMsg(const s: WideString): Integer; safecall;
    function Get_Count: Integer; safecall;
    procedure AddCount; safecall;
    procedure Set_Count(Value: Integer); safecall;
  public
    procedure Initialize; override;
  end;

implementation

uses ComServ;

function TMyObject.ShowMsg(const s: WideString): Integer;
begin
    ShowMessage(S);
    Result:= 1;
end;

function TMyObject.Get_Count: Integer;
begin
    Result:= FCount;
end;

procedure TMyObject.AddCount;
begin
    Inc(FCount);
end;

procedure TMyObject.Set_Count(Value: Integer);
begin
    FCount:= Value;
end;

procedure TMyObject.Initialize;
begin
    FCount:= 0;
   inherited;
end;

initialization
  TAutoObjectFactory.Create(ComServer, TMyObject, Class_MyObject,
    ciMultiInstance, tmApartment);
end.



unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, OleCtrls, MSScriptControl_TLB, StdCtrls, Unit2, SHDocVw;

type
  TForm1 = class(TForm)
    ScriptControl: TScriptControl;
    Memo1: TMemo;
    Button1: TButton;
    WebBrowser: TWebBrowser;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
  public
    MyObject: TMyObject;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
    ScriptControl.Reset;
    ScriptControl.Error.Clear;
    ScriptControl.AddObject('MyObject', MyObject, True);
    ScriptControl.AddObject('IE', WebBrowser.DefaultInterface, False);
    ScriptControl.ExecuteStatement(Memo1.Lines.Text);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
    MyObject:= TMyObject.Create;
    MyObject.ObjAddRef;
    
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
    MyObject.ObjRelease;
end;

end.



原创粉丝点击