2008. február 22., péntek

How to search for a certain font style in a TRichEdit


Problem/Question/Abstract:

How to search for a certain font style in a TRichEdit

Answer:

Finding all bold-faced words in a TRichEdit control:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
    ComCtrls;

type
  TForm1 = class(TForm)
    RichEdit1: TRichEdit;
    ListBox1: TListBox;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
var
  S: string;
  wordstart, wordend: Integer;
begin
  listbox1.clear;
  listbox1.setfocus;
  S := richedit1.text;
  wordstart := 0;
  repeat
    {find start of next word}
    repeat
      Inc(wordstart);
    until
      (wordstart > Length(S)) or IsCharAlpha(S[wordstart]);
    if wordstart <= Length(S) then
    begin
      {find end of word}
      wordend := wordstart;
      repeat
        Inc(wordend);
      until
        (wordend > Length(S)) or not IsCharAlpha(S[wordend]);
      {we have a word, select it in the rich edit}
      with richedit1 do
      begin
        selstart := wordstart - 1; {character index is 0 based!}
        sellength := wordend - wordstart;
        {check the attributes}
        if (fsBold in SelAttributes.Style) and (caBold in
          SelAttributes.ConsistentAttributes) then
          {we have a winna, add it to the listbox}
          listbox1.items.add(Copy(S, wordstart, wordend - wordstart));
      end;
      wordstart := wordend;
    end;
  until
    wordstart >= Length(S);
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése