call back to C# function from within VBScript run with msscript.ocx

1.1k Views Asked by At

I want to use msscript.ocx to call VBScript from C#, and allow the VBScript code to call back to functions in the C# program.

For example, in the following VBScript code, Clicktext is a custom C# function in the same clsss that is using msscript.ocx to run the VBScript.

For i=0 to i=4

    Clicktext("Auto")

Next

The Clicktext function shoud be called 5 times.

Is there any way to do it?

1

There are 1 best solutions below

2
On BEST ANSWER

This ComVisible console application with a reference to Interop.MSScriptControl:

// !! http://sandsprite.com/blogs/index.php?uid=11&pid=83

using System;
using MSScriptControl;

//class test has to support IDispatch to AddObject(). So make the assembly ComVisible
//via AssemblyInfo.cs or [assembly: System.Runtime.InteropServices.ComVisible(true)]

namespace MsScTest {
    public class CsHelper {
        public int increment(int y) { return ++y; }
    }

    class Program {
        public static MSScriptControl.ScriptControl sc = new ScriptControl();
        static void Main(string[] args) {
            sc.Language = "VBScript";
            sc.AddObject("CsHelper", new CsHelper(), true);
            sc.AddCode(@"
Function inc(n)
  inc = CsHelper.increment(n)
End Function
MsgBox inc(4711), 0, 'With a little help from my friend CsHelper'
".Replace("'", "\""));
            return;
        }
    }
}

pudding:

---------------------------
With a little help from my friend CsHelper
---------------------------
4712
---------------------------
OK   
---------------------------

demonstrates how to call a method of a C# object from VBScript code added to a MSScriptControl.