I'd like to create a COM object in C#, and use it via IDispatch from JScript. That part is pretty simple.
I also want to implement simple callbacks on the COM object, similar to the event exposed by the XmlHttpRequest object that is usable in a browser. That model allows Javascript to attach event handlers like this:
var xmlhttp = new ActiveXObject("MSXML.XMLHTTP");
xmlhttp.onReadyStateChange = function() {
...
};
I want my client-side JScript code to look like this:
var myObject = new ActiveXObject("MyObject.ProgId");
myObject.onMyCustomEvent = function(..args here..) {
...
};
What does the C# code look like? I'd like the general case - I'd like to be able to pass arguments back to the Javascript fn.
I've seen How can I make an ActiveX control written with C# raise events in JavaScript when clicked? , but the answers there look really complicated to implement, and complicated to use.
From this article, it seems that XMLHttpRequest events are not COM events. The onreadystatechange
is a property of type IDispatch
. When script clients set that property to a function, JScript marshals it as an IDispatch object.
The only problem that remains is then to invoke the IDispatch from C#.
Since it's COM, start by defining an interface. Let's keep it simple.
Then, the implementation:
The main trick is the
FireEvent
method. This worked for me.Compile that all together, register it with regasm:
...And then use it from JScript like this:
It works.
You can also call it from VBScript:
To pass parameters back from C# to JScript with this approach, I think objects need to be IDispatch, but of course you can send back simple values marshaled as string, int, and so on which are marshaled as you would expect.
For example, modify the C# code to send back a reference to itself, and the number 42.
Then, you can get that in jscript like so:
Or in VBScript like so:
NB: You can define your jscript event handler function to accept fewer args than are sent by the C# object when invoking the "event". In my experience you need to design the event handler in VBScript to explicitly accept the correct number of arguments.
Wow, wow! May be easy?
then use these build command
On jscript (wsh):
source: msdn
Enjoy!