How to sink COM events from Silverlight?
I want to raise an event from a .NET class, and receive this event in Silverlight code (out-of-browser, using the COM interop support added in SL4).
Can anyone point out the problem in my code? Do I maybe need to do more attribute-decorated interface boilerplate to get this working?
Code:
Rather than write native COM code, I am writing .NET code and exposing it via COM interop.
My event-raising .NET class looks like this:
using System;
namespace TestComInterop2 {
public class TestClass {
public event EventHandler TestEvent;
public void Fire() {
if (TestEvent != null)
TestEvent(this, EventArgs.Empty);
}
}
}
My SL4 client code looks like this:
...
private delegate void HandlerDelegate(dynamic sender, dynamic eventArgs);
private void TestEventSinking(object sender, RoutedEventArgs e)
{
// Create instance of COM-registered .NET class
var testClass = AutomationFactory.CreateObject("TestComInterop2.TestClass");
// Subscribe to event (second line fails with System.Exception)
//
// "Failed to add event handler. Possible reasons include: the object does not
// support this or any events, or something failed while adding the event."
//
AutomationEve开发者_C百科nt testEvent = AutomationFactory.GetEvent(testClass, "TestEvent");
testEvent.AddEventHandler(new HandlerDelegate(HandleTestEvent));
// Fire the event
testClass.Fire();
}
private void HandleTestEvent(object sender, object eventargs)
{
MessageBox.Show("Event fired");
}
...
Use the [ComSourceInterface] attribute on your class. The relevant MSDN Library topic is here.
精彩评论