0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot Horner!! The solution provided by you worked for me.
Just one big notice: adding derived classes as script Object's may end up as major screwup. I was adding class derived from Form. And method on that class was never called. As soon I removed ": Form" code started working. PS: above code helped me locate this problem, so +1 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.