Click here to Skip to main content
15,845,330 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was trying to combine different styles in a CRichEditCtrl control but couldn't find out how.
My goal:
to send this string "Normal text:\n```some code```\nMore text\n" and have the 'some code' part shown differently.

What I have tried:

I tried the following but the text looks the same.

DWORD CALLBACK EditStreamCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb)
{
    CString* pStr = reinterpret_cast<CString*>(dwCookie);
    *pcb = pStr->GetLength() * sizeof(TCHAR);
    memcpy(pbBuff, pStr->GetBuffer(), *pcb);
    return 0;
}


void myDialog::ApplySourceCodeStyleToText(CRichEditCtrl& m_editControl)
{
    // Get the current text in the CRichEditCtrl control
    CString text;
    m_editControl.GetWindowTextW(text);

    // Find the starting and ending positions of the code portion
    int startPos = text.Find(L"```");  // Prefix with L to create wide-character string
    int endPos = text.Find(L"```", startPos + 3);  // Prefix with L to create wide-character string

    if (startPos != -1 && endPos != -1 && endPos > startPos)
    {
        // Get the code portion from the text
        CString code = text.Mid(startPos + 3, endPos - startPos - 3);

        // Define the RTF string for the source code style
        CString rtfSourceCodeStyle = L"{\\rtf1\\ansi\\deff0{\\colortbl;\\red0\\green0\\blue255;}{\\f1\\fs20\\cf1 ";
        CString rtfEnd = L"}}";

        // Combine the RTF-formatted code with the surrounding text
        CString rtfText;
        rtfText.Format(L"%s%s%s", text.Left(startPos + 3), rtfSourceCodeStyle, code);
        rtfText.AppendFormat(L"%s%s", rtfEnd, text.Mid(endPos));

        // Convert the RTF text to plain text
        CString plainText;
        EDITSTREAM es;
        es.dwCookie = reinterpret_cast<DWORD_PTR>(&plainText);
        es.pfnCallback = EditStreamCallback;
        m_editControl.StreamIn(SF_TEXT, es);

        // Set the new text with source code style
        m_editControl.SetWindowTextW(rtfText);

        // Convert the plain text to RTF and set the selection
        m_editControl.SetSel(0, -1);
        m_editControl.ReplaceSel(plainText, TRUE);
        m_editControl.SetSel(-1, 0);
    }
}
Posted
Updated 1-Jun-23 1:55am

1 solution

Michael : I do not have a direct solution but I found a sample that might prove helpful. It seems to be somewhat full-featured and it does the things you are asking about. Here it is : CAutoRichEditCtrl - automate rich edit formatting and RTF handling[^].

I hope it helps.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900