2010-01-15 36 views
1

我通過網絡發現了這段代碼。這將背景色添加到Trichedit上的選定文本:delphi 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; 

但是,我需要的是排除空格字符。有人能幫我嗎?任何想法都會有幫助嗎? 我的想法是選擇所有的空格字符,然後格式化,但我不知道如何選擇它們。 順便說一下,我使用德爾福2009年。

回答

2

@ junmats,與此代碼,您可以選擇任何單詞在一個Richedit控件。

德爾福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; 
+0

看起來這是由詞搜索的詞。 。使用這將使我的程序非常慢,因爲我有一個非常大的字符串塊..但我想這是我的答案最好的解決方案..非常感謝:-) – junmats 2010-01-18 02:00:30