从不同的进程设置RichEdit的文本颜色

2024-09-26 18:10:17 发布

您现在位置:Python中文网/ 问答频道 /正文

从Richa控件到Richa控件的背景颜色不同。我使用python调用了下面的C代码,但它失败了(SendMessage返回0)。如果我将SCF_选择更改为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;
}

Tags: includemem控件cfcrscfsendmessagesizeof

热门问题