How to create C# Event to handle MFC Windows message from PostMessage()

不打扰是莪最后的温柔 提交于 2019-12-10 19:22:49

问题


I have a managed C++ DLL using WINSOCK. On receive it sends a custom message to a CWnd * via PostMessage(). This works fine when called from unmanaged C++. The target CWnd * is registered with the C++ class after construction using this code:

// Registers a window (CWnd *) to receive a message when a valid
// incoming data packet is received on this UdpRetrySocket. 
void CUdpRetrySocket::RegOnReceive(CWnd *i_pOnReceiveWnd, UINT i_RecvMsgId = WM_USER_RECV_DATA_AVAIL)
{
    m_pOnReceiveWnd = i_pOnReceiveWnd;
    m_RecvMsgId = i_RecvMsgId;
}

Here's the code that Posts the message to CWnd *

// If there is a pending incoming packet and there is a window
// registered for receive notification then post a message to it.
if (m_bInPktPending && m_pOnReceiveWnd != NULL)
    m_pOnReceiveWnd->PostMessage(m_RecvMsgId,
                                 (WPARAM)m_RecvSocket.LocalSockAddrIn().Port(),
                                 (LPARAM)this
                                );

I'm now using this CUdpRetrySocket class from a C# Windows Forms application. Questions:

  1. From C# Forms class how do I obtain a CWnd * to register with my C++ CUdpRetrySocket class

    FOUND ANSWER #1 HERE

// C++ Register Window Method
void RegOnReceive(System::IntPtr i_Hwnd)
   { m_pOnReceiveWnd = CWnd::FromHandle((HWND)i_Hwnd.ToPointer()); }

// C# Caller of Register Window Method
class MyForm : Form
{
    . . .
    cmdDev.RegOnReceive(Handle);
  1. How do I create an event in my C# window to capture this custom MFC style message?

  2. I need the C# app to process packets even when window is minimized. Will the C# Forms Window still receive these messages if it is minimized?

  3. Is there a better way to do this?


回答1:


Found answer to how to create event handler HERE
You simply override the Form.WndProc() virtual method, test for the specific custom message ID and pass all others on to the base class for processing.

protected override void WndProc(ref System.Windows.Forms.Message message)
{
    if (message.Msg == MY_CUSTOM_WINDOW_MSG_ID)
    {
        // PROCESS EVENT HERE
    }            
    base.WndProc(ref message);
}

Testing shows that the answer to the last question is YES. The message is sent and processed even when Form is minimized.



来源:https://stackoverflow.com/questions/11125843/how-to-create-c-sharp-event-to-handle-mfc-windows-message-from-postmessage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!