65.9K
CodeProject 正在变化。 阅读更多。
Home

C#脚本引擎教程

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.08/5 (12投票s)

2002 年 8 月 22 日

viewsIcon

142139

downloadIcon

1343

介绍如何使用 Microsoft.vsa 让你的程序拥有脚本功能

Sample Image - CSScriptEngine.gif

引言

许多现代应用程序支持脚本功能,为用户提供了一种以编程方式控制应用程序本身的方式。这项技术让用户能够根据自己的意愿控制程序的流程。 以前,微软提供了 IActiveScript 接口来访问脚本引擎。 在 .NET 框架中,微软提供了许多类来支持脚本引擎,请参考 ms-help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfMicrosoftVsa.htm。 我编写了一个示例程序来展示如何在 C# 中实现它。 在这个示例程序中,我创建了一个 winform 控件并将其放在我的示例程序中,稍后我将展示如何使用 VB 脚本调用此程序中的方法,以及使用脚本处理此控件的事件。 用户控件名为 UserControl1,它有一个方法和一个事件。

你必须实现 Microsoft.Vsa.IVsaSite,它提供你的程序和脚本引擎之间的桥梁

public class TestVsaSite : Microsoft.Vsa.IVsaSite
{
    private System.Collections.Hashtable eventInstance;

    public TestVsaSite()
    {
        eventInstance = new Hashtable();
    }

    public void AddEvent(string name, string type, object instance, 
           bool events)
    {
        eventInstance.Add(name, instance);
    }

    public void GetCompiledState(out byte[] pe, out byte[] debugInfo)
    {
    }

    public object GetEventSourceInstance(string itemName, 
            string eventSourceName)
    {
        return eventInstance[eventSourceName];
    }

    public object GetGlobalInstance(string name)
    {
        return (object)null;
    }

    public void Notify(string notify, object info)
    {
    }

    public bool OnCompilerError(IVsaError error)
    {
        return false;
    }
}

现在创建一个脚本引擎实例

m_vbEngine = new Microsoft.VisualBasic.Vsa.VsaEngine();
你可以通过调用来挂接事件
m_vbScript.AddEventSource(name, type);
m_vbTempRef = (IVsaReferenceItem)m_vbItems.CreateItem(name, 
    VsaItemType.Reference, VsaItemFlag.None);

这里是 VB 脚本示例

imports myNotClass
imports System
Public Module Vespu

#Region "Automatically generated code, do not modify"
'Automatically generated code, do not modify
'Event Sources Begin
    <System.ContextStaticAttribute()> Public WithEvents ctrlInScript _
      As myNotClass.UserControl1
'Event Sources End
'End of automatically generated code
#End Region


Sub main
End Sub

Sub ctrlInScript_tick(count As Integer) Handles ctrlInScript.tick
dim disp as string
disp = "tick counter is: " & count.ToString()
ctrlInScript.SetText(disp)
End Sub
End Module
© . All rights reserved.