完整解决方案:
1::
function SumWidth(aRichEdit: TRichEdit;aIndex: Integer): Integer;
var
p, q: TPoint;
i: Integer;
s, t: string;
begin
//aIndex 是要求的行 index
with aRichEditdo
begin
s := Lines[aIndex];
Lines[aIndex] := s + ' ';
i := SendMessage(Handle, EM_LINEINDEX, aIndex, 0);
SendMessage(Handle, EM_POSFROMCHAR, LongInt(@p), i);
SendMessage(Handle, EM_POSFROMCHAR, LongInt(@q),
i + Length(Lines[aIndex]) - 1);
Result := q.x - p.x;
Lines[aIndex] := s;
end;
end;
2::
function SumWidth(aRichEdit: TRichEdit;
aIndex: Integer): Integer;
var
i, j: Integer;
aCanvas: TCanvas;
begin
aCanvas := TCanvas.Create;
j := SendMessage(aRichEdit.Handle, EM_LINEINDEX, aIndex, 0);
Result := 0;
with aRichEditdo
i := 1 to Lines[aIndex]do
begin
SelStart := j + i - 1;
SelLength := 1;
aCanvas.Assign(SelAttributes);
Result := Result + aCanvas.TextWidth(SelText);
end;
SelLength := 0;
end;