Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

More on late binding

2009-07-13

How about an example on how to use scripting capabilities in your application, if the script control is available, without setting any references?

'Attempt to get the type for the script control.
Dim ScType As System.Type = System.Type.GetTypeFromProgID( _
"MSScriptControl.ScriptControl")

'If the prog ID is missing, Null is returned (Nothing in Visual Basic).
If ScType Is Nothing Then

    MessageBox.Show("The Script Control is not available.")

Else

    Dim Sc As Object = System.Activator.CreateInstance(ScType)

    'All is well. Configure the script control: Set language.
    Dim LanguageParameterValue() As Object = {"VBScript"}
    ScType.InvokeMember("Language", Reflection.BindingFlags.SetProperty, Nothing, Sc, _
          LanguageParameterValue, Nothing)

    'Allow UI operation (such as MsgBox).
    Dim AllowUIParameterValue() As Object = {True}
    ScType.InvokeMember("AllowUI", Reflection.BindingFlags.SetProperty, Nothing, Sc, _
          AllowUIParameterValue, Nothing)

    'Finally, set timeout to [forever].
    Dim TimeoutParameterValue() As Object = {-1}
    ScType.InvokeMember("Timeout", Reflection.BindingFlags.SetProperty, Nothing, Sc, _
          TimeoutParameterValue, Nothing)

    'Create a script.
    Dim S As New System.Text.StringBuilder()
    S.AppendLine("For A=1 To 10")
    S.AppendLine("MsgBox A")
    S.AppendLine("Next")

    'Execute the script. Error in the script will raise an exception. Use Try/Catch here.
     Dim Code() As String = {S.ToString()}
     ScType.InvokeMember("AddCode", Reflection.BindingFlags.InvokeMethod, Nothing, Sc, _
          Code, Nothing)

End If

In this example, I showed how to use the script control, if it is available. When you are writing applications that use for example Word or Excel, you might want your application to features from Word, if Word is available, but still be able to run; this is the way. Have fun!

Categories: Visual Basic 9

Tags: Late Binding, Scripting, VBScript

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips