2011-02-01 85 views
1

javascript函数我已经写了很多,我想在我的VB6应用程序使用效率和节省时间调用从VB6

是它可以调用从VB6 javascript函数的JavaScript函数?如果可能,你可以帮我一些代码吗?

+0

你为什么用javascript编写它们,如果你需要它们在VB中? – CyberDude 2011-02-01 17:47:04

+0

我曾经在JavaScript中使用过它们。由于JavaScript支持正则表达式,所以JavaScript似乎更快速地处理字符串。在VB中,你必须使用脚本控制,它有一个性能问题 – Smith 2011-02-01 18:27:20

回答

2

我毫不犹豫地这样说,但您可以使用Windows脚本控制ActiveX控件并将其嵌入到您的VB6应用程序中,然后运行您的JavaScript代码,但可能需要稍作调整,但请勿这样做。你可能会认为这对你来说是有效率和节省时间的,但事实是你将花费各种额外的时间来处理你的“解决方法”。此外,将代码移植到VB6将使其运行速度更快。如果您需要某种可扩展性,我只会使用脚本方法。

添加对脚本运行时和脚本控件1.0的引用。
注意:在本例中,变量scode是作为字符串传递给函数的javascript代码。由于代码只是一个字符串,你可以传入任何你想要的变量,但是,从代码中取回东西要复杂得多。代码可以即时创建或从文本文件中检索。

在此示例中,代码作为字符串传递,然后搜索字符串以查看它是否包含名为OnProgramLoad的函数。如果有,则调用该函数。

Public Sub OnProgramLoad(byval scode as string) 
Dim sctest As ScriptControl 

If Len(scode) < 1 Then Exit Sub 

If InStr(1, scode, "OnProgramLoad", vbTextCompare) = 0 Then Exit Sub 

Set sctest = New ScriptControl 

With sctest 
    .Language = "JScript" 
    .AllowUI = True 
    .AddObject "Application", App 
    .AddObject "Clipboard", Clipboard 
    .AddObject "Printer", Printer 
    .AddObject "Screen", Screen 
    .AddCode scode 
    .Run "OnProgramLoad" 
    End With 
Set sctest = Nothing 

End Sub 

你会好起来的移植您的程序来VB6,如果你需要访问在VB6正则表达式库有更好的方法:
http://support.microsoft.com/kb/818802

添加到微软的VBScript正则表达式5.5参考,然后移植你的代码...

Function TestRegExp(myPattern As String, myString As String) 
    'Create objects. 
    Dim objRegExp As RegExp 
    Dim objMatch As Match 
    Dim colMatches As MatchCollection 
    Dim RetStr As String 

    ' Create a regular expression object. 
    Set objRegExp = New RegExp 

    'Set the pattern by using the Pattern property. 
    objRegExp.Pattern = myPattern 

    ' Set Case Insensitivity. 
    objRegExp.IgnoreCase = True 

    'Set global applicability. 
    objRegExp.Global = True 

    'Test whether the String can be compared. 
    If (objRegExp.Test(myString) = True) Then 

    'Get the matches. 
    Set colMatches = objRegExp.Execute(myString) ' Execute search. 

    For Each objMatch In colMatches ' Iterate Matches collection. 
     RetStr = RetStr & "Match found at position " 
     RetStr = RetStr & objMatch.FirstIndex & ". Match Value is '" 
     RetStr = RetStr & objMatch.Value & "'." & vbCrLf 
    Next 
    Else 
    RetStr = "String Matching Failed" 
    End If 
    TestRegExp = RetStr 
End Function