How to create C# Event to handle MFC Windows messa

2019-07-04 19:11发布

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条回答
闹够了就滚
2楼-- · 2019-07-04 19:55

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.

查看更多
登录 后发表回答