WSH » WScript » ConnectObject

Syntax:
WScript.ConnectObject (objObject, strSubPrefix)
objObject
Receives the object whose events will be bound to event handlers in the script.
strSubPrefix
The string that will be concatenated with the name of the event being fired.

The ConnectObject method binds the events of an object to event handlers (sinks) in the currently executing script.

After a call to ConnectObject, whenever an event in objObject occurs, WSH will look for a subroutine in the currently executing script whose name is the concatenation of strSubPrefix and the name of the event being fired. If this subroutine has the correct prototype to act as an event-handler for the event, then WSH will call it and pass it the appropriate arguments. Note that WSH looks for a subroutine whose name is the direct concatenation of the specified strSubPrefix and the event name - no underscore is included in the name unless it is specified in strSubPrefix.

Examples

Code:
Set objWord = WScript.CreateObject("Word.Application")
WScript.ConnectObject objWord, "objWord_"

objWord.visible = True
blnWordVisible = True

Do While blnWordVisible
WScript.Sleep 500
Loop

Sub objWord_Quit
    blnWordVisible = False
    WScript.Echo "You quit Word."
End Sub

Sub objWord_DocumentChange
    WScript.Echo "You switched documents."
End Sub
Output:
You switched documents.
You switched documents.
You quit Word.
Explanation:

This VBScript code creates an instance of Microsoft Word and establishes event handlers for its DocumentChange and Quit events. The script sleeps until Word is closed by the user. When Word is opened, if the user opens a new document, and then closes Word, the output shown will be generated.

Language(s): VBScript
Code:
objWord = WScript.CreateObject("Word.Application")
WScript.ConnectObject(objWord, "objWord_")

objWord.visible = true
blnWordVisible = true

while (blnWordVisible)
{
    WScript.Sleep(500)
}

function objWord_Quit ()
{
    blnWordVisible = false
    WScript.Echo("You quit Word.")
}

function objWord_DocumentChange ()
{
    WScript.Echo("You switched documents.")
}
Output:
You switched documents.
You switched documents.
You quit Word.
Explanation:

This JScript code creates an instance of Microsoft Word and establishes event handlers for its DocumentChange and Quit events. The script sleeps until Word is closed by the user. When Word is opened, if the user opens a new document, and then closes Word, the output shown will be generated.

Language(s): JavaScript

See Also: