Skip to main content
 首页 » 编程设计

c#之捕捉 COM 事件

2024年02月13日17webabcd

尝试连接我们用来与 .NET 中的事物对话的 COM 库。在 VB6 中,同样的事情可以通过

private withevents _monitor as new Application 

然后我就可以做

monitor_onPrintText(byval msg as string, byval draw as boolean) 

它会起作用,只要在显示器端打印了一些东西,它就会触发事件并将东西发回给我们。但是,在 C# 中,我能够执行命令,但无法像在 VB6 中那样恢复正常。我只是很好奇我做错了什么,因为我读过的所有内容都说

_monitor.onPrintText += onPrintText;  

应该可以,但我无法触发事件。

我试过了 this codeproject project , and MSDN ,还有一堆其他资源,但我无法让这该死的东西工作!这是代码的基础,我添加了通过导入 com 对象创建的所有三个“接口(interface)”,并且我尝试了各种不同的组合。我的“启动”脚本应该返回一个 true,并触发 onPrintText 事件几次并伴随一些消息(或者至少这是它在 VB6 中所做的......)

using System; 
using monitorLib; 
 
public class MyClass  
{ 
    private Application _monitor; 
 
    public MyClass() 
    { 
        _monitor = new Application; 
        _monitor.onPrintText += onPrintText; 
 
        // Doing this runs a "script" which causes the  
        // event to fire whenever print is called from it. 
        _monitor.evaluate("run(\"startup\");");  
    } 
 
 
    public dynamic Evaluate(string pScript) 
    { 
        return _monitor.evaluate(pScript); 
    } 
 
    public void PrintText(string p_text, bool p_drawNow) 
    { 
        debug.print(p_text); 
    } 
} 

请您参考如下方法:

  public class MyClass : IApplication, IApplicationEvents, IApplicationEvents_Event 

这里出了点问题。也许这是故意的,但值得怀疑。 服务器 实现接口(interface),客户端 只是使用它们。您已经编写了服务器需要编写的代码。它必须实现服务器提供的所有接口(interface)。但是 MyClass 确实看起来像只使用服务器的客户端代码。

不确定您是如何陷入困境的,也许您一直在编写服务器代码,而从不编写客户端代码。另一种可能的解释是 COM 允许服务器实现多个生成事件的接口(interface)。不是您可以在 C# 中执行的操作。为了取得成功,您必须删除所有这些继承的接口(interface),以及您为实现它们而编写的代码。然后要么尝试:

public MyClass() { 
    _monitor = new Application(); 
    _monitor.onPrintText += onPrintText; 
} 

正如您通常所写的那样。如果默认的 [source] 接口(interface)没有实现该事件,那么您可能需要这样写:

public MyClass() { 
    _monitor = new Application; 
    var source = (IApplicationEvents_Events)_monitor; 
    source.onPrintText += onPrintText; 
} 

但这只是一个猜测,我看不到您在对象浏览器中可以看到的内容。预计它现在不起作用,您最终听取了自己的事件。