【问题标题】:call back to C# function from within VBScript run with msscript.ocx从使用 msscript.ocx 运行的 VBScript 中回调 C# 函数
【发布时间】:2013-05-04 20:04:37
【问题描述】:

我想使用 msscript.ocx 从 C# 调用 VBScript,并允许 VBScript 代码回调 C# 程序中的函数。

例如,在以下 VBScript 代码中,Clicktext 是使用 msscript.ocx 运行 VBScript 的同一 clss 中的自定义 C# 函数。

For i=0 to i=4

    Clicktext("Auto")

Next

Clicktext 函数应该被调用 5 次。

有什么办法吗?

【问题讨论】:

标签: c# vbscript controls msscriptcontrol


【解决方案1】:

这个 ComVisible 控制台应用程序引用了 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;
        }
    }
}

布丁:

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

演示如何从添加到 MSScriptControl 的 VBScript 代码中调用 C# 对象的方法。

【讨论】:

  • 非常感谢霍纳!!您提供的解决方案对我有用。
  • @Jaskaran 如果解决方案有效,请考虑 +1 并将答案标记为正确。
  • 只有一个重要的通知:将派生类添加为脚本对象可能会导致重大错误。我正在添加从表单派生的类。并且从未调用过该类的方法。我一删除“:表单”代码就开始工作了。 PS:上面的代码帮我找到了这个问题,所以+1 ;)
最近更新 更多