如何在另一个进程中通过其句柄设置窗口文本?

时间:2015-03-08 02:22:57

标签: c++ windows winapi ipc messaging

出于我的目的,我需要使用其HWND句柄为属于另一个进程的窗口设置文本。我提出了以下代码,但它似乎不起作用:

BOOL SetWindowTextInAnotherProcess(HWND hWnd, LPCTSTR pStrText)
{
    //Set text of the 'hWnd' (assuming that 'hWnd' is in another process)
    //'pStrText' = ASCIIZ string to set
    //RETURN:
    //      = TRUE if done
    BOOL bRes = FALSE;

    if(hWnd &&
        pStrText)
    {
        DWORD dwProcID = 0;
        ::GetWindowThreadProcessId(hWnd, &dwProcID);
        if(dwProcID)
        {
            HANDLE hProc = ::OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, dwProcID);
            if(hProc)
            {
                int nLn = lstrlen(pStrText);

                int ncbSzStr = (nLn + 1) * sizeof(TCHAR);
                VOID* pVMem = ::VirtualAllocEx(hProc, NULL, ncbSzStr, MEM_COMMIT, PAGE_READWRITE);
                if(pVMem)
                {
                    SIZE_T sztWrtn = 0;
                    if(::WriteProcessMemory(hProc, pVMem, pStrText, ncbSzStr, &sztWrtn))
                    {
                        if(sztWrtn == ncbSzStr)
                        {
                            DWORD_PTR dwMsgRes = 0xCCCCABAB;
                            if(::SendMessageTimeout(hWnd, WM_SETTEXT, NULL, (LPARAM)pVMem,
                                SMTO_NORMAL | SMTO_ABORTIFHUNG | SMTO_ERRORONEXIT,
                                1000 * 2,
                                &dwMsgRes))
                            {
                                //Check result
                                if(dwMsgRes != 0xCCCCABAB &&
                                    dwMsgRes == TRUE)
                                {
                                    //Done
                                    bRes = TRUE;
                                }
                            }
                        }
                    }

                    //Free mem
                    ::VirtualFreeEx(hProc, pVMem, ncbSzStr, MEM_DECOMMIT);
                }

                ::CloseHandle(hProc);
            }
        }
    }

    return bRes;
}

SendMessageTimeout返回FALSEGetLastError返回0.

知道我做错了什么吗?

PS。这两个进程在同一台桌面上都是非提升的。

0 个答案:

没有答案