简体   繁体   中英

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

I have a device that is controlled by standard win32 dlls. The device responses are sent back through an application window handle (required when connected). Right now, the only way I have to look at the messages is by overriding the WndProc inside the form, which is quite limiting.

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.

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. All I have seen shows hooks from within the same form, not from a dll.

Oh, by the way, I understand hooks are WPF compatible also, and that is a requirement here as well.

Any thoughts are much appreciated!

IMessageFilter only gives you posted messages, not sent messages. There is of course little you can do if the device code insists on using the app's main window. You'll need to add a public method to let the main app tell you what its main window's Handle value is. You can then derive your own class from NativeWindow to subclass that main window and spy on its messages. Use the AssignHandle() method and override WndProc() to snoop. Be sure to call DefWndProc() for any messages that are not device related. You also need to detect WM_CLOSE so you can un-subclass the window, call ReleaseHandle().

Why not just add a method inside the DLL that you call from WndProc?

//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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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