Advanced Application of ScriptControl in Delphi (I)
Our Windows system provides an OCX component called ScriptControl, which we can use to realize the wonderful world of script storytelling.
1. Create ScriptControl component service
First, let’s take a look at what methods and properties this component has. As shown in Figure 001, 002.
Figure 001
Figure 002
Next, we use Delphi to create component services. From Figure 001, it can be seen that the PRogID of this component is "MSScriptControl.ScriptControl". .1” . So we can create a component like this: Var sc : OleVariant;begin sc := CreateOleObject('MSScriptControl.ScriptControl.1');//Use the Language property to set the language used by the component//The language can be: VbScript, javaScript (can also be abbreviated as JScript)//Equivalent to <Script Language='JScript'> used in HTML...</Scipt> sc.Language :='Javascript';end;
2. Use Eval() to implement the simplest mathematical expression calculation
Eval() is the most commonly used method in this component, and it is also a method that is often used by people to calculate mathematical expressions. Demo Function calc(const expression: String):Integer; Var sc: OleVariant; begin //expresion := '100+5*
3' ; sc := CreateOleObject('MSScriptControl.ScriptControl.1'); sc.Language :='JavaScript'; result := StrtoInt( sc.eval(expression) ); end; Sample: 115 := calc('100+5 *
3' );
3. Implement Chinese character encryption
There are two functions in JavaScript, Escape and Unescape, which are generally used as encryption for Script in Html code. The purpose is to prevent others from directly viewing their scripts and displaying them in their garbled form.
Figure 003 Encryption: Words := 'This is a piece of Chinese character information encrypted with escape! '; //Result:%u8FD9%u
662F %u4E00%u6BB5%u7528escape%u
52A 0%u5BC6%u7684%u
6C 49%u5B57%u4FE1%u
606F %uFF01 Result := sc.Eval('escape(''+Words+''')'); Decryption: Result := sc.Eval('unescape(''+Words+''')');
4. Use JavaScript regular expressions to verify the specification of IP addresses
Here we need to use the AddCode method of ScriptControl to add custom methods. The rules for IP addresses are from
0.0.0 .0-255.255.255.255.255. The following is the code to verify the IP address: var idict,script:String;begin //IP regular idict := '^([01]?[0-9][0-9]|[01]?[0-9 ]?[0-9]|2[0-4][0-9]|25[0-5])/.'+ '([01]?[0-9][0-9]|[01 ]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])/.'+ '([01]?[0-9][0 -9]|[01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])/.'+ '([01]?[ 0-9][0-9]|[01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$'; // JavaScript custom function script:= 'function IpReg(str){'+ 'var re=new RegExp(''+ipreg+''');'+ ' return re.test(str);}'; sc.AddCode (script); //Execute function if sc.Eval('IpReg(''+Edit1.Text+''')') then ShowMessage('Correct IP address format!') else ShowMessage('Illegal IP address format !') ;end;----------------------------JoeCom(juwuyi)2005-03-19