0

我是 delphi 的新手,我试图弄清楚如何将特定的行(而不是完整的文本)从一个richtextbox 加载到另一个。

procedure TForm1.richedit1change(Sender: TObject);
var
  ms: TMemoryStream;
begin
  ms := TMemoryStream.Create;
  try
    RichEdit1.Lines.SaveToStream(ms);
    ms.Seek(0, soFromBeginning);

    RichEdit2.Lines.LoadFromStream(ms);
  finally
    ms.Free;
  end;
end;
4

1 回答 1

3

您不需要流来将文本行从一个传输TRichEdit到另一个。只需使用该Lines属性。 Lines是一种TStrings类型,所以使用它的方法来操作TRichEdit文本。

procedure TForm1.richedit1change(Sender: TObject);
var
  i: Integer;
begin
  RichEdit2.Lines.Clear;
  for i := 0 to Pred(RichEdit1.Lines.Count) do
  begin
    if YourSpecificTestFunction(i) then
      RichEdit2.Lines.Add(RichEdit1.Lines[i]);
  end;
end;

如果要保留 RTF 格式,可以使用 Zarko Gajic 描述的技术,Append or Insert RTF from one RichEdit to Another.

另一个简单的选择是使用 windows 剪贴板和 TRichEdit.Selection:

procedure CopyRichEditSelection(Source,Dest: TRichEdit);
begin
  // Copy Source.Selection to Dest via ClipBoard.
  Dest.Clear;
  if (Source.SelLength > 0) then
  begin
    Source.CopyToClipboard;        
    Dest.PasteFromClipboard;
  end;
end;

这也将保留您的格式,复制选定的部分。

如果您想在没有用户控制的情况下控制选择,请使用TRichEdit.SelStart将插入符号定位到选择开始的字符,以及SelLength选择长度。要将插入符号定位在特定行上,请使用:

RichEdit1.SelStart := RichEdit1.Perform(EM_LINEINDEX, Line, 0);

如果您不想使用 windows 剪贴板进行复制/粘贴操作,可以使用流:

Uses RichEdit;

function EditStreamOutCallback(dwCookie: DWORD_PTR; pbBuff: PByte; cb: Longint;
  var pcb: LongInt): LongInt; stdcall;
begin
  pcb := cb;
  if cb > 0 then
  begin
    TStream(dwCookie).WriteBuffer(pbBuff^, cb);
    Result := 0;
  end
  else
    Result := 1;
end;

procedure GetRTFSelection(aRichEdit: TRichEdit; intoStream: TStream);
type
  TEditStreamCallBack = function (dwCookie: DWORD_PTR; pbBuff: PByte;
    cb: Longint; var pcb: Longint): Longint; stdcall;

  TEditStream = packed record // <-- Note packed !!
    dwCookie: DWORD_PTR;
    dwError: Longint;
    pfnCallback: TEditStreamCallBack;
  end;

var
  editstream: TEditStream;
begin
  with editstream do
  begin
    dwCookie := DWORD_PTR(intoStream);
    dwError := 0;
    pfnCallback := EditStreamOutCallBack;
  end;
  aRichedit.Perform( EM_STREAMOUT, SF_RTF or SFF_SELECTION, LPARAM(@editstream));
end;

procedure CopyRichEditSelection(Source,Dest: TRichEdit);
var
  aMemStream: TMemoryStream;
begin
  Dest.Clear;
  if (Source.SelLength > 0) then
  begin
    aMemStream := TMemoryStream.Create;
    try
      GetRTFSelection(Source, aMemStream);
      aMemStream.Position := 0;
      Dest.Lines.LoadFromStream(aMemStream);
    finally
      aMemStream.Free;
    end;
  end;
end;
于 2014-02-20T09:06:30.983 回答