3

我正在尝试为来自不同进程的 Richedit 控件(类 RichEdit20W)中的特定单词设置背景和前景色。我有以下使用 python 调用的 C 代码,但它失败了(SendMessage 返回 0)。如果我将 SCF_SELECTION 更改为 SFC_ALL 或 0,它会起作用,但遗憾的是它不符合我的需要,因为我只需要将更改应用于控件中的部分文本。

这是代码:

#include <Windows.h>
#include <stdio.h>
#include <limits.h>
#include <Richedit.h>

__declspec(dllexport) LRESULT SetColour(HWND hWnd, COLORREF textColor, COLORREF bgColor)
{
    CHARRANGE cr;
    cr.cpMin = 3;
    cr.cpMax = 8;

    CHARFORMAT2 cf;
    cf.cbSize = sizeof(cf);
    cf.dwMask = CFM_COLOR | CFM_BACKCOLOR;
    cf.crTextColor = textColor;
    cf.crBackColor = bgColor;

    DWORD   dwPID;
    HANDLE  hProcess;
    LPVOID  pRemoteCR;
    LPVOID  pRemoteCF;
    SIZE_T  zWritten;
    LRESULT lResult;

    GetWindowThreadProcessId(hWnd, &dwPID);
    hProcess = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, dwPID);
    //  Allocate memory on the target process & write the CHARFORMAT2 structure there
    pRemoteCR = VirtualAllocEx(hProcess, NULL, sizeof cr, MEM_COMMIT, PAGE_READWRITE);
    WriteProcessMemory(hProcess, pRemoteCR, &cr, sizeof cr, &zWritten);
    SendMessage(hWnd, EM_EXSETSEL, 0, (LPARAM)pRemoteCR);
    VirtualFreeEx(hProcess, pRemoteCR, 0, MEM_RELEASE);

    pRemoteCF = VirtualAllocEx(hProcess, NULL, sizeof cf, MEM_COMMIT, PAGE_READWRITE);
    WriteProcessMemory(hProcess, pRemoteCF, &cf, sizeof cf, &zWritten);
    lResult = SendMessage(hWnd, EM_SETCHARFORMAT, (WPARAM)SCF_SELECTION, (LPARAM)pRemoteCF); // SCF_SELECTION
    VirtualFreeEx(hProcess, pRemoteCF, 0, MEM_RELEASE);

    return lResult;
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD dwReason,LPVOID lpvReserved)
{
    return TRUE;
}
4

0 回答 0