I need to bold some words within a RichEdit in Delphi, it works normally when there is no line break. But when I enter a line break I can not correctly select the word to apply the style.
All the examples I found have the same problem.
In this example it stores the words that will be blacked out and the color they will have and typing it will apply the formatting. But it only works until you insert a line break.
procedure TfrmRichEdit.RichEdit1KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
const
LetrasValidas = ['a'..'z', 'A'..'Z', '0'..'9', '<', '>', '!', '='];
var
iPosIni: Integer;
iPosFim: Integer;
iSelStart: Integer;
iSelLength: Integer;
iLoopFor: Integer;
sText: string;
begin
LockWindowUpdate(RichEdit1.Handle);
// Guardaremos a posição inicial
iSelStart := RichEdit1.SelStart;
iSelLength := RichEdit1.SelLength;
sText := RichEdit1.Text;
// Acharemos o inicio da palavra
iPosIni := iSelStart;
if sText[iPosIni] in LetrasValidas then
begin
for iLoopFor := iSelStart - 1 downto 0 do
begin
if sText[iLoopFor] in LetrasValidas then
iPosIni := iLoopFor
else
Break;
end;
end;
// Acharemos o final da palavra
iPosFim := iSelStart;
for iLoopFor := iSelStart + 1 to Length(RichEdit1.Text) do
begin
if RichEdit1.Text[iLoopFor] in LetrasValidas then
iPosFim := iLoopFor
else
Break;
end;
// Selecionaremos a palavra
RichEdit1.SelStart := iPosIni - 1;
RichEdit1.SelLength := (iPosFim) - RichEdit1.SelStart;
// setaremos a cor original e estilo original
RichEdit1.SelAttributes.Color := clBlack;
RichEdit1.SelAttributes.Style := [];
// Atribuiremos a nova cor e estilo caso encontre a palavra
for iLoopFor := 0 to High(APalavras) do
begin
if UpperCase(APalavras[iLoopFor].DS_PALAVRA) = UpperCase(RichEdit1.SelText) then
begin
RichEdit1.SelAttributes.Color := APalavras[iLoopFor].VR_COR;
RichEdit1.SelAttributes.Style := APalavras[iLoopFor].ESTILO;
Break;
end;
end;
// Posicionaremos o cursor na posição original
RichEdit1.SelStart := iSelStart;
RichEdit1.SelLength := iSelLength;
LockWindowUpdate(0);
end;