Search code examples
c#sendmessagewndproc

WndProc does not work when window is out of focus


I wanted to use SendMessage to a WM_COPYDATA from a global hook dll, and then send it to myMainwindow WndProc. WndProc only listens to procs when it is the active screen, and does not receive the message being sent by the dll when it is out of focus.

Is this a limitation of WndProc? are there better alternatives to this?


Solution

  • I found out the problem to be the HWND being used on my SendMessage call. It has to be shared by all dlls like so:

    #pragma data_seg("Shared")
    //our hook handle which will be returned by calling SetWindowsHookEx function
    HHOOK hkKey = NULL;
    HINSTANCE hInstHookDll = NULL;  //our global variable to store the instance of our DLL
    HWND pHWnd = NULL; // global variable to store the mainwindow handle
    #pragma data_seg() //end of our data segment
    
    #pragma comment(linker,"/section:Shared,rws")
    // Tell the compiler that Shared section can be read,write and shared
    
    __declspec(dllexport) LRESULT CALLBACK procCharMsg(int nCode, WPARAM wParam, LPARAM lParam)
    //this is the hook procedure
    {
        //a pointer to hold the MSG structure that is passed as lParam
        MSG* msg;
        //to hold the character passed in the MSG structure's wParam
        char charCode;
        if (nCode >= 0 && nCode == HC_ACTION)
            //if nCode is less than 0 or nCode
            //is not HC_ACTION we will call CallNextHookEx
        {
            //lParam contains pointer to MSG structure.
            msg = (MSG*)lParam;
            if (msg->message == WM_CHAR)
                //we handle only WM_CHAR messages
            {
                SendMessage(pHWnd, WM_CHAR, (WPARAM)msg->message, (LPARAM)0); // This should now work globally
            }
        }
        return CallNextHookEx(hkKey, nCode, wParam, lParam);
    }
    
    // called by main app to establish a pointer of itself to the dlls
    extern "C" __declspec(dllexport) int SetParentHandle(HWND hWnd) {
        pHWnd = hWnd;
        if (pHWnd == NULL) {
            return 0;
        }
    
        return 1;
    }
    

    I should have posted my code along with the problem, since little things are always pretty hard to spot alone.