In C# I can write event handlers as follows:
var wdApp = new Microsoft.Office.Interop.Word.Application();
wdApp.DocumentBeforeSave += (Document doc, ref bool saveAsUI, ref bool cancel) => {
//do stuff here
};
In VBA/VB6, I can use static event handling:
Dim WithEvents wdApp As Word.Application
Private Sub wdApp_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
'do stuff here
End Sub
I would prefer to use dynamic event handling. However, in JScript, even when using static event handling with the syntax described here:
var wdApp = new ActiveXObject('Word.Application');
wdApp.Visible = true;
function wdApp::Quit() {
window.alert('Quit');
};
it fails:
0x800a138f - JScript runtime error: Object expected
Also, static event handling is an option in VBA/VB6, because the declarations can be marked Private
. However, in JScript, both the variable and the handler have to be declared in the global scope.
Two questions:
How can I handle events of Automation-created objects with JScript in an HTA environment? (Note: I know that it is possible in WSH using a prefix passed to
CreateObject
, and a function namedwdApp_Quit
, but I am looking for an HTA solution.)How can I do this without polluting the global scope?
There is an older question here.
varName::eventName() { }
which will be called on theeventName
event for the global-scopedvarName
object. This mechanism is available in both WScript and in HTAs. But I would like something that doesn't require global function declarations and global variables; similar to the C# mechanism --wdApp
doesn't have to be a global variable in order to attach / remove handlers. – RickiesetTimeout
see my answer. – Rickie