我正在尝试实现一个基于此示例在Excel中引发COM事件的C#COM服务器:http://msdn.microsoft.com/en-us/library/dd8bf0x3(v=vs.90).aspx
我的问题类似于以下
Exposing C# COM server events to Delphi client applications
我正在使用Visual Studio 2015,net 4.5和Excel 2013
以下是示例测试代码
namespace XLServer
{
[ComVisible(true)]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
public interface Events
{
void NewEvent();
}
[ComVisible(true)]
[ComSourceInterfaces(typeof(Events))]
public class MessageHandler
{
public delegate void NewEventDelegate();
public event NewEventDelegate NewEvent;
public System.Threading.Timer EventTimer;
public MessageHandler() { StartEvents(); }
public void FireNewEvent()
{
Debug.Print("Fire New Event");
if (NewEvent != null) NewEvent();
}
public void StartEvents()
{
if (EventTimer == null) EventTimer = new System.Threading.Timer(MessageEvent, null, 1000, 2000);
}
private void MessageEvent(object o)
{
FireNewEvent();
}
}
}
这是VB代码
Public WithEvents mh As MessageHandler
Public status As String
Public Sub Class_Initialize()
Set mh = New MessageHandler
status = "Initialized"
End Sub
' Events and methods are matched by name and signature.
Public Sub mh_NewEvent()
On Error Resume Next
MsgBox ("NewEvent Fired")
End Sub
当我在Excel中启动MessageHandler时,我在FireNewEvent方法中出现以下错误
Fire New Event
Exception thrown: 'System.Reflection.TargetException' in mscorlib.dll
An unhandled exception of type 'System.Reflection.TargetException' occurred in mscorlib.dll
Additional information: Object does not match target type.
任何建议都将不胜感激。 谢谢!
更新
问题是由于使用了System.Threading.Timer。
使用System.Windows.Forms.Timer
时,它可以正常工作namespace XLServer
{
[ComVisible(true)]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)]
public interface Events
{
void NewEvent();
}
[ComVisible(true)]
[ComSourceInterfaces(typeof(Events))]
public class MessageHandler
{
public delegate void NewEventDelegate();
public event NewEventDelegate NewEvent;
public System.Windows.Forms.Timer EventTimer;
public MessageHandler() { StartEvents(); }
public void FireNewEvent()
{
Debug.Print("Fire New Event");
if (NewEvent != null) NewEvent();
}
private void StartEvents()
{
if (EventTimer == null) EventTimer = new Timer();
EventTimer.Interval = 5000;
EventTimer.Tick += new EventHandler(timer_Tick);
EventTimer.Start();
}
private void timer_Tick(object sender, EventArgs e)
{
FireNewEvent();
}
}