我正在尝试为来自不同进程的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;
}