PostMessage(), SendMessage not working in ATL dll

2019-09-06 20:41发布

问题:

sorry, my english skill is very low.

i make a ATL(C++) dll. and handled by VB. i make under base code.

WaitAndReadData, Thread_WaitAndReadData is working.

but, ::SendMessage, ::PostMessage is not working in Thread_WaitAndReadData or WaitAndReadData. and breakpoint not working in Get_Data_Messagehandler. (+ another function call.)

#define WM_SERVERTHREADFIREEVENT (WM_USER+2)
BEGIN_MSG_MAP(CHello)
CHAIN_MSG_MAP(CComControl<CHello>)
MESSAGE_HANDLER(WM_SERVERTHREADFIREEVENT, GetData_Messagehandler)
DEFAULT_REFLECTION_HANDLER()
END_MSG_MAP()

-

static DWORD WINAPI Thread_WaitAndReadData(LPVOID pParam)

-

STDMETHODIMP CHello::WaitAndReadData(BSTR* ret_Result)
{
    // TODO: Add your implementation code here

    DWORD dwThreadID;

    thread = CreateThread(NULL, 0, Thread_WaitAndReadData, (LPVOID)this, 0, &dwThreadID);

    return S_OK;
}

-

DWORD WINAPI CHello::Thread_WaitAndReadData(LPVOID pParam)
{

CHello* hello = (CHello*)pParam;

::SendMessage(hello->m_hWnd, WM_SERVERTHREADFIREEVENT, (WPARAM)NULL, (LPARAM)NULL);

return S_OK;
}

-

LRESULT CHello::GetData_Messagehandler(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
MessageBox(L"GetData_Messagehandler", L"asd", MB_OK);

return 0;
}

回答1:

  1. Even though MSDN states that there is no marshaling of WM_USER + x messages in cross-process sending, if my memory serves me right you might have troubles with cross-thread sending as well. In this case use RegisterWindowMessage API to obtain "sendable" WM_xxx identifier rather than harcoding it using a #define

  2. Don't use bare CreateThread, use AtlCreateThread instead (or, _beginthreadex). See why.

Another reason to not receive messages on window thread is thread deadlock or window creation on thread that does not have a message pump later on, in both cases a message might be sent but there is no dispatching it to window. You can also use Spy++ tool (spyxx.exe in Visual Studio Comment\Tools directory) to make sure that the message in question is indeed being sent to the window.