gpt4 book ai didi

delphi - delphi TRichEdit设置背景颜色,不包括空格

转载 作者:行者123 更新时间:2023-12-03 19:45:17 26 4
gpt4 key购买 nike

我在网上找到了此代码。这会将背景色添加到Trichedit上的选定文本中:

uses
RichEdit;

procedure RE_SetSelBgColor(RichEdit: TRichEdit; AColor: TColor);
var
Format: CHARFORMAT2;
begin
FillChar(Format, SizeOf(Format), 0);
with Format do
begin
cbSize := SizeOf(Format);
dwMask := CFM_BACKCOLOR;
crBackColor := AColor;
Richedit.Perform(EM_SETCHARFORMAT, SCF_SELECTION, Longint(@Format));
end;
end;

// Example: Set clYellow background color for the selected text.
procedure TForm1.Button1Click(Sender: TObject);
begin
RE_SetSelBgColor(RichEdit1, clYellow);
end;


但是,我需要排除空格字符。有人能帮我吗?有什么想法会有所帮助吗?
我的想法是选择所有空格字符,然后对其进行格式化,但是我不知道如何选择它们。
顺便说一句,我正在使用delphi 2009。

最佳答案

@junmats,使用此代码,您可以在richedit控件中选择任何单词。

在Delphi 2010和Windows 7中测试

uses
RichEdit;

procedure SetWordBackGroundColor(RichEdit : TRichEdit; aWord : String;AColor: TColor);
var
Format: CHARFORMAT2;
Index : Integer;
Len : Integer;
begin
FillChar(Format, SizeOf(Format), 0);
Format.cbSize := SizeOf(Format);
Format.dwMask := CFM_BACKCOLOR;
Format.crBackColor := AColor;

Index := 0;
Len := Length(RichEdit.Lines.Text) ;
Index := RichEdit.FindText(aWord, Index, Len, []);

while Index <> -1 do
begin
RichEdit.SelStart := Index;
RichEdit.SelLength := Length(aWord) ;
RichEdit.Perform(EM_SETCHARFORMAT, SCF_SELECTION, Longint(@Format));
Index := RichEdit.FindText(aWord,Index + Length(aWord),Len, []) ;
end;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
SetWordBackGroundColor(RichEdit1,' ',clYellow);// will mark all spaces
end;


如果您想选择除空格以外的所有单词,则可以执行以下操作

Procedure GetListofWords(Text : String; var ListofWords : TStringList);
var
DummyStr : String;
FoundWord : String;
begin
DummyStr := Text;
FoundWord := '';
if (Length(Text) = 0) then exit;

while (Pos(' ', DummyStr) > 0) do
begin
FoundWord := Copy(DummyStr, 1, Pos(' ', DummyStr) - 1);
ListofWords.Add(FoundWord);
DummyStr := Copy(DummyStr, Pos(' ', DummyStr) + 1, Length(DummyStr) - Length(FoundWord) + 1);
end;

if (Length(DummyStr) > 0) then
ListofWords.Add(DummyStr);

end;



procedure TForm1.Button1Click(Sender: TObject);
var
ListofWords : TStringList;
i : integer;
begin
ListofWords:=TStringList.Create;
try
GetListofWords(RichEdit1.Lines.Text,ListofWords);
if ListofWords.Count>0 then
for i:=0 to ListofWords.Count - 1 do
SetWordBackGroundColor(RichEdit1,ListofWords[i],clYellow);
finally
ListofWords.Clear;
ListofWords.Free;
end;
end;

关于delphi - delphi TRichEdit设置背景颜色,不包括空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2069889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com