如何在程序中执行动态生成的Delphi代码

如何在程序中执行动态生成的Delphi代码 


经常发现有人提这类问题,或者提问内容最后归结成这种问题 


前些阵子有位高手写了一个“执行动态生成的代码”,这是真正的高手,我没那种功力,我只会投机取巧。 


这里提供三种方法,都是借助第三方的组件来实现的。 


1、MicroSoft Windows Script Control(http://www.microsoft.com/downloads/details.aspx?FamilyID=d7e31492-2595-49e6-8c02-1426fec693ac&DisplayLang=en) 
   这是微软的东西,OCX的,我对OCX的东西一向没什么好感,:)但总算是解决问题的一个方法。 
   到以上地址下载回来sct10en.exe,这是个安装程序,安装完成以后,在安装目录里有一个msscript.ocx,就是它了。 
   在Delphi中Import OCX...导入安装,在窗体上添加一个TScriptControl类的实例。 
   设置好它的Scriptanguage属性:VBScript,JScript...IE认识的它都认识,没有Object Pascal?不要急,好戏总是放在后头嘛... 
   以VbScript为例: 
     运行脚本:ScriptControl1.ExecuteStatement('msgbox("Runing....")'); 
     计算公式:ShowMessage(scriptcontrol1.Eval('1+1')); 
   
   优点:皇家的东西,相信它,没错的 
   缺点:发布程序带个OCX,只能支持微软的Script 


2、Dream Collection中的DCScripter(ftp://202.117.210.28/file/dream4.rar) 
   安装好以后在控件面板DreamCompany里面有一个向右的黑色箭头,就是它了。 
   以VbScript为例: 
   运行脚本:DCScripter1.Script.Add('msgbox("Script Runing...")'); 
             DCScripter1.Run; 
   计算公式:ShowMessage(DCScripter1.Evaluate('1+1')); 


   优点:VCL的,除支持微软的脚本以外,还支持Perl,Python 
   缺点:还是不支持Object Pascal...(别打,就来了...) 


3、DelphiWebScriptII(http://prdownloads.sourceforge.net/dws/dws2src11.zip) 
   这个东西好啊,功能超强,太强了,太强了,真强... 
   安装完成以后,将TDelphiWebScriptII,Tdws2GUIFunctions加入窗体,引用dws2Exprs单元。 
   运行脚本: 
   var 
     prg: TProgram; 
   begin 
     prg := DelphiWebScriptII1.Compile('ShowMessage(''hi'');'); 
     prg.Execute; 
   end; 
   这个东西是用稍微复杂一点,不过看看Demo吧,接下来的造化就看你自己的了。 


   优点:VCL的,功能超强,支持Object Pascal... 
   缺点:只支持Object Pascal... 


以上三个各有忧缺点,大家可能比较欣赏DelphiWebScript的功能,但是我觉得如果是给用户使用的话,还是Dream Scripter比较好,毕竟VbScript等比较容易为用户所接受。其实现在很多网管等都很习惯于利用系统提供的COM对象,使用纯脚本进行编程。很方便的。 

MSScriptControl_TLB.pas

unit MSScriptControl_TLB;

// ************************************************************************ //
// WARNING                                                                    
// -------                                                                    
// The types declared in this file were generated from data read from a       
// Type Library. If this type library is explicitly or indirectly (via        
// another type library referring to this type library) re-imported, or the
// 'Refresh' command of the Type Library Editor activated while editing the   
// Type Library, the contents of this file will be regenerated and all        
// manual modifications will be lost.                                         
// ************************************************************************ //

// PASTLWTR : $Revision: 1.1 $
// File generated on 2005-12-20 13:43:49 from Type Library described below.

// ************************************************************************  //
// Type Lib: C:\WINNT\System32\msscript.ocx (1)
// LIBID: {0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}
// LCID: 0
// Helpfile: C:\WINNT\System32\MSSCRIPT.HLP
// DepndLst: 
//   (1) v2.0 stdole, (C:\WINNT\system32\stdole2.tlb)
//   (2) v4.0 StdVCL, (C:\WINNT\system32\stdvcl40.dll)
// Errors:
//   Hint: TypeInfo 'Procedure' changed to 'Procedure_'
//   Hint: Parameter 'Object' of IScriptModuleCollection.Add changed to 'Object_'
//   Hint: Parameter 'Object' of IScriptControl.AddObject changed to 'Object_'
// ************************************************************************ //
{$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. 
{$WARN SYMBOL_PLATFORM OFF}
{$WRITEABLECONST ON}
{$VARPROPSETTER ON}
interface

uses Windows, ActiveX, Classes, Graphics, OleCtrls, OleServer, StdVCL, Variants;
  


// *********************************************************************//
// GUIDS declared in the TypeLibrary. Following prefixes are used:        
//   Type Libraries     : LIBID_xxxx                                      
//   CoClasses          : CLASS_xxxx                                      
//   DISPInterfaces     : DIID_xxxx                                       
//   Non-DISP interfaces: IID_xxxx                                        
// *********************************************************************//
const
  // TypeLibrary Major and minor versions
  MSScriptControlMajorVersion = 1;
  MSScriptControlMinorVersion = 0;

  LIBID_MSScriptControl: TGUID = '{0E59F1D2-1FBE-11D0-8FF2-00A0D10038BC}';

  IID_IScriptProcedure: TGUID = '{70841C73-067D-11D0-95D8-00A02463AB28}';
  IID_IScriptProcedureCollection: TGUID = '{70841C71-067D-11D0-95D8-00A02463AB28}';
  IID_IScriptModule: TGUID = '{70841C70-067D-11D0-95D8-00A02463AB28}';
  IID_IScriptModuleCollection: TGUID = '{70841C6F-067D-11D0-95D8-00A02463AB28}';
  IID_IScriptError: TGUID = '{70841C78-067D-11D0-95D8-00A02463AB28}';
  IID_IScriptControl: TGUID = '{0E59F1D3-1FBE-11D0-8FF2-00A0D10038BC}';
  DIID_DScriptControlSource: TGUID = '{8B167D60-8605-11D0-ABCB-00A0C90FFFC0}';
  CLASS_Procedure_: TGUID = '{0E59F1DA-1FBE-11D0-8FF2-00A0D10038BC}';
  CLASS_Procedures: TGUID = '{0E59F1DB-1FBE-11D0-8FF2-00A0D10038BC}';
  CLASS_Module: TGUID = '{0E59F1DC-1FBE-11D0-8FF2-00A0D10038BC}';
  CLASS_Modules: TGUID = '{0E59F1DD-1FBE-11D0-8FF2-00A0D10038BC}';
  CLASS_Error: TGUID = '{0E59F1DE-1FBE-11D0-8FF2-00A0D10038BC}';
  CLASS_ScriptControl: TGUID = '{0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC}';

// *********************************************************************//
// Declaration of Enumerations defined in Type Library                    
// *********************************************************************//
// Constants for enum ScriptControlStates
type
  ScriptControlStates = TOleEnum;
const
  Initialized = $00000000;
  Connected = $00000001;

type

// *********************************************************************//
// Forward declaration of types defined in TypeLibrary                    
// *********************************************************************//
  IScriptProcedure = interface;
  IScriptProcedureDisp = dispinterface;
  IScriptProcedureCollection = interface;
  IScriptProcedureCollectionDisp = dispinterface;
  IScriptModule = interface;
  IScriptModuleDisp = dispinterface;
  IScriptModuleCollection = interface;
  IScriptModuleCollectionDisp = dispinterface;
  IScriptError = interface;
  IScriptErrorDisp = dispinterface;
  IScriptControl = interface;
  IScriptControlDisp = dispinterface;
  DScriptControlSource = dispinterface;

// *********************************************************************//
// Declaration of CoClasses defined in Type Library                       
// (NOTE: Here we map each CoClass to its Default Interface)              
// *********************************************************************//
  Procedure_ = IScriptProcedure;
  Procedures = IScriptProcedureCollection;
  Module = IScriptModule;
  Modules = IScriptModuleCollection;
  Error = IScriptError;
  ScriptControl = IScriptControl;


// *********************************************************************//
// Declaration of structures, unions and aliases.                         
// *********************************************************************//
  PPSafeArray1 = ^PSafeArray; {*}
  POleVariant1 = ^OleVariant; {*}


// *********************************************************************//
// Interface: IScriptProcedure
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C73-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptProcedure = interface(IDispatch)
    ['{70841C73-067D-11D0-95D8-00A02463AB28}']
    function Get_Name: WideString; safecall;
    function Get_NumArgs: Integer; safecall;
    function Get_HasReturnValue: WordBool; safecall;
    property Name: WideString read Get_Name;
    property NumArgs: Integer read Get_NumArgs;
    property HasReturnValue: WordBool read Get_HasReturnValue;
  end;

// *********************************************************************//
// DispIntf:  IScriptProcedureDisp
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C73-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptProcedureDisp = dispinterface
    ['{70841C73-067D-11D0-95D8-00A02463AB28}']
    property Name: WideString readonly dispid 0;
    property NumArgs: Integer readonly dispid 100;
    property HasReturnValue: WordBool readonly dispid 101;
  end;

// *********************************************************************//
// Interface: IScriptProcedureCollection
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C71-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptProcedureCollection = interface(IDispatch)
    ['{70841C71-067D-11D0-95D8-00A02463AB28}']
    function Get__NewEnum: IUnknown; safecall;
    function Get_Item(Index: OleVariant): IScriptProcedure; safecall;
    function Get_Count: Integer; safecall;
    property _NewEnum: IUnknown read Get__NewEnum;
    property Item[Index: OleVariant]: IScriptProcedure read Get_Item; default;
    property Count: Integer read Get_Count;
  end;

// *********************************************************************//
// DispIntf:  IScriptProcedureCollectionDisp
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C71-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptProcedureCollectionDisp = dispinterface
    ['{70841C71-067D-11D0-95D8-00A02463AB28}']
    property _NewEnum: IUnknown readonly dispid -4;
    property Item[Index: OleVariant]: IScriptProcedure readonly dispid 0; default;
    property Count: Integer readonly dispid 1;
  end;

// *********************************************************************//
// Interface: IScriptModule
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C70-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptModule = interface(IDispatch)
    ['{70841C70-067D-11D0-95D8-00A02463AB28}']
    function Get_Name: WideString; safecall;
    function Get_CodeObject: IDispatch; safecall;
    function Get_Procedures: IScriptProcedureCollection; safecall;
    procedure AddCode(const Code: WideString); safecall;
    function Eval(const Expression: WideString): OleVariant; safecall;
    procedure ExecuteStatement(const Statement: WideString); safecall;
    function Run(const ProcedureName: WideString; var Parameters: PSafeArray): OleVariant; safecall;
    property Name: WideString read Get_Name;
    property CodeObject: IDispatch read Get_CodeObject;
    property Procedures: IScriptProcedureCollection read Get_Procedures;
  end;

// *********************************************************************//
// DispIntf:  IScriptModuleDisp
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C70-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptModuleDisp = dispinterface
    ['{70841C70-067D-11D0-95D8-00A02463AB28}']
    property Name: WideString readonly dispid 0;
    property CodeObject: IDispatch readonly dispid 1000;
    property Procedures: IScriptProcedureCollection readonly dispid 1001;
    procedure AddCode(const Code: WideString); dispid 2000;
    function Eval(const Expression: WideString): OleVariant; dispid 2001;
    procedure ExecuteStatement(const Statement: WideString); dispid 2002;
    function Run(const ProcedureName: WideString; var Parameters: {??PSafeArray}OleVariant): OleVariant; dispid 2003;
  end;

// *********************************************************************//
// Interface: IScriptModuleCollection
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C6F-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptModuleCollection = interface(IDispatch)
    ['{70841C6F-067D-11D0-95D8-00A02463AB28}']
    function Get__NewEnum: IUnknown; safecall;
    function Get_Item(Index: OleVariant): IScriptModule; safecall;
    function Get_Count: Integer; safecall;
    function Add(const Name: WideString; var Object_: OleVariant): IScriptModule; safecall;
    property _NewEnum: IUnknown read Get__NewEnum;
    property Item[Index: OleVariant]: IScriptModule read Get_Item; default;
    property Count: Integer read Get_Count;
  end;

// *********************************************************************//
// DispIntf:  IScriptModuleCollectionDisp
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C6F-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptModuleCollectionDisp = dispinterface
    ['{70841C6F-067D-11D0-95D8-00A02463AB28}']
    property _NewEnum: IUnknown readonly dispid -4;
    property Item[Index: OleVariant]: IScriptModule readonly dispid 0; default;
    property Count: Integer readonly dispid 1;
    function Add(const Name: WideString; var Object_: OleVariant): IScriptModule; dispid 2;
  end;

// *********************************************************************//
// Interface: IScriptError
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C78-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptError = interface(IDispatch)
    ['{70841C78-067D-11D0-95D8-00A02463AB28}']
    function Get_Number: Integer; safecall;
    function Get_Source: WideString; safecall;
    function Get_Description: WideString; safecall;
    function Get_HelpFile: WideString; safecall;
    function Get_HelpContext: Integer; safecall;
    function Get_Text: WideString; safecall;
    function Get_Line: Integer; safecall;
    function Get_Column: Integer; safecall;
    procedure Clear; safecall;
    property Number: Integer read Get_Number;
    property Source: WideString read Get_Source;
    property Description: WideString read Get_Description;
    property HelpFile: WideString read Get_HelpFile;
    property HelpContext: Integer read Get_HelpContext;
    property Text: WideString read Get_Text;
    property Line: Integer read Get_Line;
    property Column: Integer read Get_Column;
  end;

// *********************************************************************//
// DispIntf:  IScriptErrorDisp
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {70841C78-067D-11D0-95D8-00A02463AB28}
// *********************************************************************//
  IScriptErrorDisp = dispinterface
    ['{70841C78-067D-11D0-95D8-00A02463AB28}']
    property Number: Integer readonly dispid 201;
    property Source: WideString readonly dispid 202;
    property Description: WideString readonly dispid 203;
    property HelpFile: WideString readonly dispid 204;
    property HelpContext: Integer readonly dispid 205;
    property Text: WideString readonly dispid -517;
    property Line: Integer readonly dispid 206;
    property Column: Integer readonly dispid -529;
    procedure Clear; dispid 208;
  end;

// *********************************************************************//
// Interface: IScriptControl
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {0E59F1D3-1FBE-11D0-8FF2-00A0D10038BC}
// *********************************************************************//
  IScriptControl = interface(IDispatch)
    ['{0E59F1D3-1FBE-11D0-8FF2-00A0D10038BC}']
    function Get_Language: WideString; safecall;
    procedure Set_Language(const pbstrLanguage: WideString); safecall;
    function Get_State: ScriptControlStates; safecall;
    procedure Set_State(pssState: ScriptControlStates); safecall;
    procedure Set_SitehWnd(phwnd: Integer); safecall;
    function Get_SitehWnd: Integer; safecall;
    function Get_Timeout: Integer; safecall;
    procedure Set_Timeout(plMilleseconds: Integer); safecall;
    function Get_AllowUI: WordBool; safecall;
    procedure Set_AllowUI(pfAllowUI: WordBool); safecall;
    function Get_UseSafeSubset: WordBool; safecall;
    procedure Set_UseSafeSubset(pfUseSafeSubset: WordBool); safecall;
    function Get_Modules: IScriptModuleCollection; safecall;
    function Get_Error: IScriptError; safecall;
    function Get_CodeObject: IDispatch; safecall;
    function Get_Procedures: IScriptProcedureCollection; safecall;
    procedure _AboutBox; safecall;
    procedure AddObject(const Name: WideString; const Object_: IDispatch; AddMembers: WordBool); safecall;
    procedure Reset; safecall;
    procedure AddCode(const Code: WideString); safecall;
    function Eval(const Expression: WideString): OleVariant; safecall;
    procedure ExecuteStatement(const Statement: WideString); safecall;
    function Run(const ProcedureName: WideString; var Parameters: PSafeArray): OleVariant; safecall;
    property Language: WideString read Get_Language write Set_Language;
    property State: ScriptControlStates read Get_State write Set_State;
    property SitehWnd: Integer read Get_SitehWnd write Set_SitehWnd;
    property Timeout: Integer read Get_Timeout write Set_Timeout;
    property AllowUI: WordBool read Get_AllowUI write Set_AllowUI;
    property UseSafeSubset: WordBool read Get_UseSafeSubset write Set_UseSafeSubset;
    property Modules: IScriptModuleCollection read Get_Modules;
    property Error: IScriptError read Get_Error;
    property CodeObject: IDispatch read Get_CodeObject;
    property Procedures: IScriptProcedureCollection read Get_Procedures;
  end;

// *********************************************************************//
// DispIntf:  IScriptControlDisp
// Flags:     (4560) Hidden Dual NonExtensible OleAutomation Dispatchable
// GUID:      {0E59F1D3-1FBE-11D0-8FF2-00A0D10038BC}
// *********************************************************************//
  IScriptControlDisp = dispinterface
    ['{0E59F1D3-1FBE-11D0-8FF2-00A0D10038BC}']
    property Language: WideString dispid 1500;
    property State: ScriptControlStates dispid 1501;
    property SitehWnd: Integer dispid 1502;
    property Timeout: Integer dispid 1503;
    property AllowUI: WordBool dispid 1504;
    property UseSafeSubset: WordBool dispid 1505;
    property Modules: IScriptModuleCollection readonly dispid 1506;
    property Error: IScriptError readonly dispid 1507;
    property CodeObject: IDispatch readonly dispid 1000;
    property Procedures: IScriptProcedureCollection readonly dispid 1001;
    procedure _AboutBox; dispid -552;
    procedure AddObject(const Name: WideString; const Object_: IDispatch; AddMembers: WordBool); dispid 2500;
    procedure Reset; dispid 2501;
    procedure AddCode(const Code: WideString); dispid 2000;
    function Eval(const Expression: WideString): OleVariant; dispid 2001;
    procedure ExecuteStatement(const Statement: WideString); dispid 2002;
    function Run(const ProcedureName: WideString; var Parameters: {??PSafeArray}OleVariant): OleVariant; dispid 2003;
  end;

// *********************************************************************//
// DispIntf:  DScriptControlSource
// Flags:     (4112) Hidden Dispatchable
// GUID:      {8B167D60-8605-11D0-ABCB-00A0C90FFFC0}
// *********************************************************************//
  DScriptControlSource = dispinterface
    ['{8B167D60-8605-11D0-ABCB-00A0C90FFFC0}']
    procedure Error; dispid 3000;
    procedure Timeout; dispid 3001;
  end;

// *********************************************************************//
// The Class CoProcedure_ provides a Create and CreateRemote method to          
// create instances of the default interface IScriptProcedure exposed by              
// the CoClass Procedure_. The functions are intended to be used by             
// clients wishing to automate the CoClass objects exposed by the         
// server of this typelibrary.                                            
// *********************************************************************//
  CoProcedure_ = class
    class function Create: IScriptProcedure;
    class function CreateRemote(const MachineName: string): IScriptProcedure;
  end;

// *********************************************************************//
// The Class CoProcedures provides a Create and CreateRemote method to          
// create instances of the default interface IScriptProcedureCollection exposed by              
// the CoClass Procedures. The functions are intended to be used by             
// clients wishing to automate the CoClass objects exposed by the         
// server of this typelibrary.                                            
// *********************************************************************//
  CoProcedures = class
    class function Create: IScriptProcedureCollection;
    class function CreateRemote(const MachineName: string): IScriptProcedureCollection;
  end;

// *********************************************************************//
// The Class CoModule provides a Create and CreateRemote method to          
// create instances of the default interface IScriptModule exposed by              
// the CoClass Module. The functions are intended to be used by             
// clients wishing to automate the CoClass objects exposed by the         
// server of this typelibrary.                                            
// *********************************************************************//
  CoModule = class
    class function Create: IScriptModule;
    class function CreateRemote(const MachineName: string): IScriptModule;
  end;

// *********************************************************************//
// The Class CoModules provides a Create and CreateRemote method to          
// create instances of the default interface IScriptModuleCollection exposed by              
// the CoClass Modules. The functions are intended to be used by             
// clients wishing to automate the CoClass objects exposed by the         
// server of this typelibrary.                                            
// *********************************************************************//
  CoModules = class
    class function Create: IScriptModuleCollection;
    class function CreateRemote(const MachineName: string): IScriptModuleCollection;
  end;

// *********************************************************************//
// The Class CoError provides a Create and CreateRemote method to          
// create instances of the default interface IScriptError exposed by              
// the CoClass Error. The functions are intended to be used by             
// clients wishing to automate the CoClass objects exposed by the         
// server of this typelibrary.                                            
// *********************************************************************//
  CoError = class
    class function Create: IScriptError;
    class function CreateRemote(const MachineName: string): IScriptError;
  end;


// *********************************************************************//
// OLE Control Proxy class declaration
// Control Name     : TScriptControl
// Help String      : Control to host scripting engines that understand the ActiveX Scripting interface
// Default Interface: IScriptControl
// Def. Intf. DISP? : No
// Event   Interface: DScriptControlSource
// TypeFlags        : (34) CanCreate Control
// *********************************************************************//
  TScriptControl = class(TOleControl)
  private
    FOnError: TNotifyEvent;
    FOnTimeout: TNotifyEvent;
    FIntf: IScriptControl;
    function  GetControlInterface: IScriptControl;
  protected
    procedure CreateControl;
    procedure InitControlData; override;
    function Get_Modules: IScriptModuleCollection;
    function Get_Error: IScriptError;
    function Get_CodeObject: IDispatch;
    function Get_Procedures: IScriptProcedureCollection;
  public
    procedure _AboutBox;
    procedure AddObject(const Name: WideString; const Object_: IDispatch; AddMembers: WordBool);
    procedure Reset;
    procedure AddCode(const Code: WideString);
    function Eval(const Expression: WideString): OleVariant;
    procedure ExecuteStatement(const Statement: WideString);
    function Run(const ProcedureName: WideString; var Parameters: PSafeArray): OleVariant;
    property  ControlInterface: IScriptControl read GetControlInterface;
    property  DefaultInterface: IScriptControl read GetControlInterface;
    property Modules: IScriptModuleCollection read Get_Modules;
    property Error: IScriptError read Get_Error;
    property CodeObject: IDispatch index 1000 read GetIDispatchProp;
    property Procedures: IScriptProcedureCollection read Get_Procedures;
  published
    property Language: WideString index 1500 read GetWideStringProp write SetWideStringProp stored False;
    property State: TOleEnum index 1501 read GetTOleEnumProp write SetTOleEnumProp stored False;
    property SitehWnd: Integer index 1502 read GetIntegerProp write SetIntegerProp stored False;
    property Timeout: Integer index 1503 read GetIntegerProp write SetIntegerProp stored False;
    property AllowUI: WordBool index 1504 read GetWordBoolProp write SetWordBoolProp stored False;
    property UseSafeSubset: WordBool index 1505 read GetWordBoolProp write SetWordBoolProp stored False;
    property OnError: TNotifyEvent read FOnError write FOnError;
    property OnTimeout: TNotifyEvent read FOnTimeout write FOnTimeout;
  end;

procedure Register;

resourcestring
  dtlServerPage = 'ActiveX';

implementation

uses ComObj;

class function CoProcedure_.Create: IScriptProcedure;
begin
  Result := CreateComObject(CLASS_Procedure_) as IScriptProcedure;
end;

class function CoProcedure_.CreateRemote(const MachineName: string): IScriptProcedure;
begin
  Result := CreateRemoteComObject(MachineName, CLASS_Procedure_) as IScriptProcedure;
end;

class function CoProcedures.Create: IScriptProcedureCollection;
begin
  Result := CreateComObject(CLASS_Procedures) as IScriptProcedureCollection;
end;

class function CoProcedures.CreateRemote(const MachineName: string): IScriptProcedureCollection;
begin
  Result := CreateRemoteComObject(MachineName, CLASS_Procedures) as IScriptProcedureCollection;
end;

class function CoModule.Create: IScriptModule;
begin
  Result := CreateComObject(CLASS_Module) as IScriptModule;
end;

class function CoModule.CreateRemote(const MachineName: string): IScriptModule;
begin
  Result := CreateRemoteComObject(MachineName, CLASS_Module) as IScriptModule;
end;

class function CoModules.Create: IScriptModuleCollection;
begin
  Result := CreateComObject(CLASS_Modules) as IScriptModuleCollection;
end;

class function CoModules.CreateRemote(const MachineName: string): IScriptModuleCollection;
begin
  Result := CreateRemoteComObject(MachineName, CLASS_Modules) as IScriptModuleCollection;
end;

class function CoError.Create: IScriptError;
begin
  Result := CreateComObject(CLASS_Error) as IScriptError;
end;

class function CoError.CreateRemote(const MachineName: string): IScriptError;
begin
  Result := CreateRemoteComObject(MachineName, CLASS_Error) as IScriptError;
end;

procedure TScriptControl.InitControlData;
const
  CEventDispIDs: array [0..1] of DWORD = (
    $00000BB8, $00000BB9);
  CControlData: TControlData2 = (
    ClassID: '{0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC}';
    EventIID: '{8B167D60-8605-11D0-ABCB-00A0C90FFFC0}';
    EventCount: 2;
    EventDispIDs: @CEventDispIDs;
    LicenseKey: nil (*HR:$00000000*);
    Flags: $00000000;
    Version: 401);
begin
  ControlData := @CControlData;
  TControlData2(CControlData).FirstEventOfs := Cardinal(@@FOnError) - Cardinal(Self);
end;

procedure TScriptControl.CreateControl;

  procedure DoCreate;
  begin
    FIntf := IUnknown(OleObject) as IScriptControl;
  end;

begin
  if FIntf = nil then DoCreate;
end;

function TScriptControl.GetControlInterface: IScriptControl;
begin
  CreateControl;
  Result := FIntf;
end;

function TScriptControl.Get_Modules: IScriptModuleCollection;
begin
    Result := DefaultInterface.Modules;
end;

function TScriptControl.Get_Error: IScriptError;
begin
    Result := DefaultInterface.Error;
end;

function TScriptControl.Get_CodeObject: IDispatch;
begin
    Result := DefaultInterface.CodeObject;
end;

function TScriptControl.Get_Procedures: IScriptProcedureCollection;
begin
    Result := DefaultInterface.Procedures;
end;

procedure TScriptControl._AboutBox;
begin
  DefaultInterface._AboutBox;
end;

procedure TScriptControl.AddObject(const Name: WideString; const Object_: IDispatch; 
                                   AddMembers: WordBool);
begin
  DefaultInterface.AddObject(Name, Object_, AddMembers);
end;

procedure TScriptControl.Reset;
begin
  DefaultInterface.Reset;
end;

procedure TScriptControl.AddCode(const Code: WideString);
begin
  DefaultInterface.AddCode(Code);
end;

function TScriptControl.Eval(const Expression: WideString): OleVariant;
begin
  Result := DefaultInterface.Eval(Expression);
end;

procedure TScriptControl.ExecuteStatement(const Statement: WideString);
begin
  DefaultInterface.ExecuteStatement(Statement);
end;

function TScriptControl.Run(const ProcedureName: WideString; var Parameters: PSafeArray): OleVariant;
begin
  Result := DefaultInterface.Run(ProcedureName, Parameters);
end;

procedure Register;
begin
  RegisterComponents('ActiveX',[TScriptControl]);
end;

end.
RegExp.vbs
function GetUrlFile(Url)
    Set RegObject = New RegExp 
    With RegObject
    .Pattern = "\w+\.\w+(?!.)"
    .IgnoreCase = True
    .Global = True
    End With
    Set matchs =  RegObject.Execute(Url)
    If matchs.Count > 0 Then
        For Each mach in matchs
            GetUrlFile=mach.value
        Next
    End If
    Set RegObject = nothing
end function 

Unit_FormMain.pas

unit Unit_FormMain;

interface

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

type
  TFormMain = class(TForm)
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    TabSheet2: TTabSheet;
    TabSheet3: TTabSheet;
    mmo_result: TMemo;
    Button1: TButton;
    mmo_FunGetUrlFile: TMemo;
    edt_formula: TEdit;
    Button2: TButton;
    mmo_FileDirCode: TMemo;
    edt_www: TEdit;
    edt_input: TEdit;
    Button3: TButton;
    Label1: TLabel;
    Label2: TLabel;
    edt_output: TEdit;
    edt_result: TEdit;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    function CallFunction(a_strCode, a_strProcName: WideString;
      const a_Params: oleVariant; IsVBScript: Boolean= True): OleVariant;
    { Private declarations }
  public
    { Public declarations }
  end;

var
  FormMain: TFormMain;

implementation

uses MSScriptControl_TLB, ActiveX;

{$R *.dfm}

function TFormMain.CallFunction(a_strCode, a_strProcName: WideString;
  const a_Params: oleVariant; IsVBScript: Boolean): OleVariant;
var
  Parameters: PSafeArray;
  l_Script: TScriptControl;
begin
  //mmo_FunGetUrlFile.Lines.LoadFromFile('RegExp.vbs');
  l_Script:= TScriptControl.Create(nil);
  if IsVBScript then l_Script.Language := 'VbScript'
  else l_Script.Language := 'JScript';
  l_Script.AllowUI:= True;
  l_Script.AddCode(a_strCode);
  try
    // 转化为安全数组
    Parameters := PSafeArray(TVarData(a_Params).VArray);
    // 调用函数
    Result := l_Script.Run(a_strProcName, Parameters);
  except
    Application.MessageBox(PChar(string('出错代码:'+l_Script.Error.Text+#13#10+
      '出错行:'+ IntToStr(l_Script.Error.Line)+#13#10+
      '出错原因:'+ l_Script.Error.Description)),'ERROR', MB_ICONEXCLAMATION);
  end;
  l_Script.Free;
end;

procedure TFormMain.Button1Click(Sender: TObject);
var
  a_var: OleVariant;
begin
  a_var := VarArrayCreate([0, 0], varVariant);
  a_var[0] := edt_www.Text;
  mmo_result.Lines.Add(CallFunction(mmo_FunGetUrlFile.Text, 'GetUrlFile', a_var));
end;

function Calculate(a_strFormula: string):Double;
var
  Script: TScriptControl;
begin
  try
    Script := TScriptControl.Create(nil);
    Script.Language := 'VbScript';
    Result := Script.Eval(a_strFormula);
  except
    result := 0;
  end;
end;

procedure TFormMain.Button2Click(Sender: TObject);
var
  ret: Double;
begin
  ret:= Calculate(edt_formula.Text);
  edt_result.Text:= FloatToStr(ret);
end;

procedure TFormMain.Button3Click(Sender: TObject);
var
  a_var: OleVariant;
begin
  a_var := VarArrayCreate([0, 0], varVariant);
  a_var[0] := edt_input.Text;
  edt_output.Text:= CallFunction(mmo_FileDirCode.Text, 'ParseFileDir', a_var, False);
end;

end.
Unit_FormMain.dfm

object FormMain: TFormMain
  Left = 361
  Top = 224
  Width = 452
  Height = 411
  Caption = 'MS ScriptControl Demo'
  Color = clBtnFace
  Font.Charset = GB2312_CHARSET
  Font.Color = clWindowText
  Font.Height = -12
  Font.Name = #23435#20307
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 12
  object PageControl1: TPageControl
    Left = 0
    Top = 0
    Width = 444
    Height = 376
    ActivePage = TabSheet2
    Align = alClient
    TabIndex = 1
    TabOrder = 0
    object TabSheet1: TTabSheet
      Caption = #20989#25968#35299#26512
      object Label1: TLabel
        Left = 0
        Top = 201
        Width = 24
        Height = 12
        Caption = #20256#20837
      end
      object Label2: TLabel
        Left = 0
        Top = 223
        Width = 24
        Height = 12
        Caption = #20256#20986
      end
      object mmo_FileDirCode: TMemo
        Left = 0
        Top = 0
        Width = 436
        Height = 193
        Align = alTop
        HideSelection = False
        Lines.Strings = (
          'function ParseFileDir(a_strFileName)'
          '{    '
          '  var l_FunNo;'
          '  var l_BaseDir;'
          '  var result;'
          '  l_BaseDir = "D:\\X'#39033#30446'\\";'
          '  l_FunNo = a_strFileName.substring(0, 5);'
          '  result = l_BaseDir+l_FunNo + '#39'\\'#39'+a_strFileName;'
          '  return result;'
          '}')
        ScrollBars = ssBoth
        TabOrder = 0
      end
      object Button3: TButton
        Left = 272
        Top = 196
        Width = 75
        Height = 25
        Caption = #36816#34892
        TabOrder = 1
        OnClick = Button3Click
      end
      object edt_input: TEdit
        Left = 36
        Top = 197
        Width = 230
        Height = 20
        TabOrder = 2
        Text = 'CF514_Tform_main_CHS.xml'
      end
      object edt_output: TEdit
        Left = 36
        Top = 221
        Width = 230
        Height = 20
        TabOrder = 3
      end
    end
    object TabSheet2: TTabSheet
      Caption = #35745#31639#20844#24335
      ImageIndex = 1
      object edt_formula: TEdit
        Left = 24
        Top = 24
        Width = 257
        Height = 20
        TabOrder = 0
        Text = 'LOG(SQR(1+2)+3)'
      end
      object Button2: TButton
        Left = 24
        Top = 56
        Width = 75
        Height = 25
        Caption = #35745#31639
        TabOrder = 1
        OnClick = Button2Click
      end
      object edt_result: TEdit
        Left = 24
        Top = 96
        Width = 257
        Height = 20
        TabOrder = 2
      end
    end
    object TabSheet3: TTabSheet
      Caption = #27491#21017#34920#36798#24335
      ImageIndex = 2
      object mmo_result: TMemo
        Left = 0
        Top = 226
        Width = 425
        Height = 118
        TabOrder = 0
      end
      object Button1: TButton
        Left = 350
        Top = 197
        Width = 75
        Height = 25
        Caption = #36816#34892
        TabOrder = 1
        OnClick = Button1Click
      end
      object mmo_FunGetUrlFile: TMemo
        Left = 0
        Top = 0
        Width = 425
        Height = 193
        Lines.Strings = (
          'function GetUrlFile(Url)'
          '    Set RegObject = New RegExp '
          '    With RegObject'
          '    .Pattern = "\w+\.\w+(?!.)"'
          '    .IgnoreCase = True'
          '    .Global = True'
          '    End With'
          '    Set matchs =  RegObject.Execute(Url)'
          '    If matchs.Count > 0 Then'
          '        For Each mach in matchs'
          '            GetUrlFile=mach.value'
          '        Next'
          '    End If'
          '    Set RegObject = nothing'
          'end function ')
        ScrollBars = ssBoth
        TabOrder = 2
      end
      object edt_www: TEdit
        Left = 0
        Top = 200
        Width = 348
        Height = 20
        TabOrder = 3
        Text = 'http://blog.csdn.net/jie115/archive/2004/09/15/104900.aspx'
      end
    end
  end
end



### 回答1: Delphi是一种编程语言和开发环境,广泛用于软件开发。通过使用Delphi,我们可以生成代码流程图来帮助我们更好地理解和分析程序执行过程。 在Delphi生成代码流程图通常有以下几个步骤: 1. 设计程序结构:在Delphi,我们使用可视化界面来设计程序的界面和功能,可以拖拽各种控件到窗体上进行布局。同时,我们可以在界面上添加按钮、菜单等事件控件,以及组织代码的结构,例如模块划分、函数和过程定义等。 2. 编写代码:在Delphi,我们可以使用Pascal语言编写代码。根据程序的需求,我们可以在各个事件和过程编写相应的代码,实现程序的功能。编写代码时,我们可以通过代码补全和代码提示等功能提高编码效率。 3. 执行程序:在编写完代码后,我们可以通过编译程序生成执行文件。运行程序时,我们可以观察程序执行过程,调试程序的错误,并根据需要进行相应的修改和优化。 4. 生成代码流程图:在Delphi,有一些工具可以帮助我们生成代码流程图,例如FlowChart插件。通过安装并使用这些工具,我们可以将已编写的代码转换为图形化的流程图。在流程图,我们可以清晰地看到程序各个部分的执行顺序和逻辑关系,有助于我们更好地理解程序执行流程。 总的来说,在Delphi生成代码流程图是一项有助于程序设计和分析的工作。通过生成代码流程图,我们可以更好地了解和掌握程序执行过程,进而进行必要的优化和调试。这样可以提高程序的质量和效率,同时也便于其他开发者理解和维护我们的代码。 ### 回答2: Delphi是一种广泛使用的集成开发环境(IDE),用于以对象为基础的编程。它提供了一个强大的工具集,包括快速生成代码和流程图的功能。 使用Delphi生成代码的流程如下: 1. 首先,使用Delphi的可视化界面设计工具创建一个新的窗体或其他控件。在设计界面上,可以使用各种控件和组件,如按钮、文本框、复选框等,来构建用户界面。 2. 在设计界面上的控件上双击,进入事件处理程序代码编辑器。在代码编辑器,可以编写执行该控件特定事件时所需的代码。例如,在按钮的单击事件编写代码,实现按钮被单击时执行的操作。 3. 使用Delphi的对象浏览器来查找并选择需要的类、函数和方法。对象浏览器提供了一个组织和浏览Delphi各种对象的界面。 4. 在代码编辑器编写代码来创建、修改和操作对象。Delphi使用Pascal语言作为基础,所以需要熟悉Pascal语法和相关的Delphi库函数。 5. Delphi还提供了一组强大的调试工具,可以帮助定位和解决代码的错误。可以使用单步调试、断点等功能来逐行执行代码,并观察代码变量的值和状态。 6. 在编写代码的过程,可以随时生成流程图来可视化代码的结构和逻辑。这可以帮助理清程序执行路径,发现潜在的问题或改进程序的可读性。 通过以上步骤,可以在Delphi生成代码并创建一个完整的应用程序Delphi的集成开发环境使得代码生成和调试过程更加简化和高效。无论是初学者还是有经验的开发者,都可以使用Delphi来创建功能丰富且高效的应用程序。 ### 回答3: Delphi是一种流行的编程语言和集成开发环境(IDE),可用于开发桌面、移动设备和Web应用程序Delphi提供了一套强大的工具和库,能够帮助开发者快速构建功能强大的应用程序Delphi开发过程生成代码和流程图是非常重要的一环。 首先,Delphi代码生成是通过使用Delphi IDE的设计窗口和代码编辑器来实现的。在设计窗口,开发者可以使用可视化设计器来创建界面、布局和组件等。设计窗口提供了丰富的工具和组件库,使开发者能够轻松定制和编辑应用程序的外观和行为。 在创建界面和布局后,开发者需要编写相应的代码来实现应用程序的逻辑和功能。在Delphi代码编辑器提供了代码编写和编辑的环境,开发者可以使用Pascal语言来编写代码。Pascal是Delphi的主要编程语言,它具有简单易懂和结构化的特点,使得代码编写更加方便和高效。 代码生成的流程一般包括以下几个步骤: 1. 设计应用程序的界面和布局,选择和放置所需的组件。 2. 在设计窗口设置组件的属性和事件,以确定它们的外观和行为。 3. 在代码编辑器编写所需的代码,实现应用程序的逻辑和功能。 4. 编译和运行应用程序,测试其功能和效果。 5. 根据需要进行调试和优化,修复可能存在的错误和问题。 在代码生成过程Delphi IDE提供了许多辅助工具和功能,如代码自动完成、调试器、版本控制和集成测试等,使开发者能够更加高效地完成代码编写和调试工作。 在生成代码的同时,Delphi IDE还可以自动生成应用程序的流程图。这可以通过使用Delphi的集成调试器来实现,调试器可以跟踪代码执行流程并可视化显示。开发者可以在代码编辑器设置断点,以便在调试过程观察应用程序执行路径和变量取值等信息。根据调试器提供的信息,开发者可以生成应用程序的流程图,以便更好地理解和分析代码执行过程。 总之,通过Delphi代码生成和流程图,开发者可以更加有效地开发和调试应用程序Delphi的强大工具和功能使得代码编写、调试和优化变得更加简单和高效,同时提高了开发效率和代码质量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值