2007. december 3., hétfő

How to set tabstops in a TRichEdit


Problem/Question/Abstract:

How can I set the positions for tabstops in general? I mean, they should be active when a new TRichEdit is opened or when an open TRichEdit is filled with text via LoadFromFile. I tried it with paragraph.tab but it doesn't do what I want.

Answer:

The property is somewhat screwed up, best use the API way directly: The positions need to be specified in twips (1/1440 inch) for the EM_SETPARAFORMAT message. The following method sets tabstops every 5 average character positions, based on the current paragraphs font.

procedure TForm1.Button2Click(Sender: TObject);
const
  tabs: array[0..5] of Integer = (5, 10, 15, 20, 25, 30);
  teststring = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var
  pf: TParaFormat;
  i: Integer;
  charwidth: Integer;
begin
  FillChar(pf, sizeof(pf), 0);
  pf.cbSize := SizeOf(pf);
  pf.dwmask := PFM_TABSTOPS;
  pf.cTabCount := 6;
  Canvas.Font.Assign(richedit1.SelAttributes);
  {average charwidth in twips}
  charwidth := (Canvas.TextWidth(teststring) * 1440) div (Screen.PixelsPerInch *
    Length(teststring));
  for i := 0 to High(tabs) do
    pf.rgxTabs[i] := tabs[i] * charwidth;
  if richedit1.perform(EM_SETPARAFORMAT, 0, Integer(@pf)) = 0 then
    ShowMessage('Failed');
end;

Add the Richedit unit to your Uses clause. If you do this setting on an empty richedit control it will become the default for new text entered. If you read in formatted text you would have to do a selectAll, then set the tabstops,to make them effective for the loaded text.

Nincsenek megjegyzések:

Megjegyzés küldése