简体   繁体   English

如何在 c# 中收听来自 DLL 的消息

[英]How can I listen to messages from an DLL in c#

I have a device that is controlled by standard win32 dlls.我有一个由标准 win32 dll 控制的设备。 The device responses are sent back through an application window handle (required when connected).设备响应通过应用程序 window 句柄(连接时需要)发回。 Right now, the only way I have to look at the messages is by overriding the WndProc inside the form, which is quite limiting.现在,我必须查看消息的唯一方法是覆盖表单内的 WndProc,这是非常有限的。

My original intention was to isolate as much as possible the device bare handling from the application by placing everything inside a dll, but this dependency is keeping me from achieving it.我的初衷是通过将所有内容放在 dll 中,尽可能地将设备裸处理与应用程序隔离开来,但这种依赖性使我无法实现它。

I need some sort of hook that will allow me to peek at the messages being received by the Form (a la WndProc) but from my dll.我需要某种钩子,让我可以查看 Form(a la WndProc)收到的消息,但来自我的 dll。 All I have seen shows hooks from within the same form, not from a dll.我所看到的都显示了来自同一表格的钩子,而不是来自 dll。

Oh, by the way, I understand hooks are WPF compatible also, and that is a requirement here as well.哦,顺便说一句,我知道钩子也兼容 WPF,这也是这里的要求。

Any thoughts are much appreciated!任何想法都非常感谢!

IMessageFilter only gives you posted messages, not sent messages. IMessageFilter 只为您提供已发布的消息,而不是已发送的消息。 There is of course little you can do if the device code insists on using the app's main window.如果设备代码坚持使用应用程序的主 window,那么您当然无能为力。 You'll need to add a public method to let the main app tell you what its main window's Handle value is.您需要添加一个公共方法,让主应用程序告诉您其主窗口的 Handle 值是什么。 You can then derive your own class from NativeWindow to subclass that main window and spy on its messages.然后,您可以从 NativeWindow 派生您自己的 class 以子类化该主 window 并监视其消息。 Use the AssignHandle() method and override WndProc() to snoop.使用 AssignHandle() 方法并覆盖 WndProc() 以进行监听。 Be sure to call DefWndProc() for any messages that are not device related.对于任何与设备无关的消息,请务必调用 DefWndProc()。 You also need to detect WM_CLOSE so you can un-subclass the window, call ReleaseHandle().您还需要检测 WM_CLOSE,以便取消 window 的子类,调用 ReleaseHandle()。

Why not just add a method inside the DLL that you call from WndProc?为什么不在从 WndProc 调用的 DLL 中添加一个方法?

//In the DLL
public bool HandleMessage(/*args go here that I forget*/) {
    if(/*message is for me*/) {
        //handle it
        return true;
    }
    return false;
}

//in WndProc
if(MyObject.HandleMessage(/*args*/)) {
    return true;
}
//do whatever else

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM