将事件处理程序附加到 Com 事件:InvalidOperationException (S7-PLCSIM)

c3n*_*try 4 c# com events plc

我正在尝试将一个事件处理程序附加到一个COM 对象的事件。但我得到一个 InvalidOperationException。

using S7PROSIMLib;

private S7ProSim ps = new S7ProSim();

ps.Connect();
ps.SetScanMode(ScanModeConstants.SingleScan);
ps.BeginScanNotify();

try {
    ps.ScanFinished += Ps_ScanFinished;
    //IS7ProSimEvents_ScanFinishedEventHandler scanFinishedDelegate = new IS7ProSimEvents_ScanFinishedEventHandler(Ps_ScanFinished);
    //ps.ScanFinished += scanFinishedDelegate;
}
catch (InvalidOperationException ex)
{
    Console.WriteLine(ex.Source);
    Console.WriteLine(ex.InnerException);
    Console.WriteLine(ex.Message);
    Console.WriteLine(ex.StackTrace);
}

private void Ps_ScanFinished(object ScanInfo)
{
    Console.WriteLine("Event fired");
} 
Run Code Online (Sandbox Code Playgroud)

输出是:

event invocation for COM objects requires event to be attributed with DispIdAttribute
   at System.Runtime.InteropServices.ComAwareEventInfo.GetDataForComInvocation(EventInfo eventInfo, Guid& sourceIid, Int32& dispid)
   at System.Runtime.InteropServices.ComAwareEventInfo.AddEventHandler(Object target, Delegate handler)
   at PiPLCSimBridge.Form1.Form1_Load(Object sender, EventArgs e) in C:\PiPLCSimBridge\Form1.cs:Line 72.
Run Code Online (Sandbox Code Playgroud)

我也尝试使用注释掉的代码,但得到了相同的异常。

像这样附加事件应该可以工作,这是一个使用相同 COM 接口的流行工具 就是这样做的。

我的代码有什么问题?

dss*_*539 6

幸运的是,我最近在使用完全相同的 COM 库时遇到了完全相同的错误。

问题是Embed Interop Typesprosim参考中的设置引起的。

我通过这里的讨论发现了这个事实 。

因此,在项目参考部分中,检查 prosim 参考的属性。确保Embed Interop Types没有设置。