如何避免重复SendMessage

时间:2011-08-18 14:06:28

标签: c++ winapi hook dry sendmessage

我遇到了一个问题:我使用DLL中的一个过程中的SendMessage与主窗口进行通信; procedure是一个钩子程序,它允许主窗口知道在编辑框中点击鼠标右键的时间;它还发送编辑框的句柄。它运行良好,除了这个错误:程序运行时没有断点主窗口收到两次相同的消息(在本例中为WM_APP),而如果我在钩子程序或处理WM_APP消息的块中放置一个断点,则消息是考虑一次。有关进一步说明,请问我。遵循钩子过程的代码和处理WM_APP消息的块的代码。感谢

挂钩程序

MYDLL_API LRESULT CALLBACK mouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
// processes the message
if(nCode >= 0)
{
    // if user clicked with mouse right button
    if(wParam != NULL && (wParam == WM_RBUTTONDOWN || wParam == WM_RBUTTONUP))
    {
        wchar_t *s = (wchar_t*) malloc(CLASSNAMELEN*sizeof(wchar_t));
        //MessageBox(mainHwnd, (LPCWSTR)L"Captured mouse right button", (LPCWSTR)L"Test", MB_OK);
        MOUSEHOOKSTRUCT *m = (MOUSEHOOKSTRUCT*) lParam;
        GetClassName(m->hwnd, (LPWSTR) s, CLASSNAMELEN);
        //MessageBox(mainHwnd, (LPCWSTR) s, (LPCWSTR)L"Test", MB_OK);
        // only if user clicked on a edit box
        if(wcsncmp(s, L"Edit", 4) == 0)
            SendMessage(mainHwnd, WM_APP, 0, (LPARAM) lParam);
        free(s);
        s = NULL;
    }
}

// calls next hook in chain
return CallNextHookEx(NULL, nCode, wParam, lParam);
}

阻止处理WM_APP消息的主程序

case WM_APP:
    {
        //MessageBox(hWnd, (LPCWSTR)L"Received WM_APP", (LPCWSTR)L"Test", MB_OK);
        // copies text from the edit box
        MOUSEHOOKSTRUCT *m = (MOUSEHOOKSTRUCT*) lParam;
        int n = GetWindowTextLength(m->hwnd);
        // if text has been inserted
        if(n > 0 && n < 1024)
        {
            wchar_t *s = (wchar_t*) malloc((n+1)*sizeof(wchar_t));
            // gets text
            GetWindowText(m->hwnd, (LPWSTR) s, n+1);
            s[n] = (wchar_t) 0;
            //MessageBox(hWnd, (LPCWSTR)s, (LPCWSTR)L"Test", MB_OK);
            // saves text in database
            stateClassPointer->insertInList(s); 
        }
    }
    break;

1 个答案:

答案 0 :(得分:3)

这可能是因为您正在发送WM_RBUTTONDOWN和WM_RBUTTONUP的消息,即按下右键和释放时的消息。

当你调试时,调试器会吃掉WM_RBUTTONUP,所以你没有得到它。

PS:你不应该使用PostMessage()代替SendMessage(),只是为了安全吗?