如何将整个 Listview 的字符串复制到 delphi 中的剪贴板?

How do I copy the strings of an entire Listview to my clipboard in delphi?

我想将列表视图中的所有行和列复制到我的剪贴板中。我尝试使用 Clipboard.Astext := SavedDataLb.Items.Text 但这显然不起作用,因为 Listviews 没有 Text 属性。我还考虑过使用 ListView 中的内置 CopyToClipboard 函数,但遗憾的是,该函数也不存在。有办法吗?

您需要编写自己的函数,对于 VCL 列表视图,它可能看起来像这样列出:

procedure ListViewCopyToClipboard(ListView: TListView);
// Copy the list view contents to the clipboard, as text with one tab-delimited line per row.

  function ReplaceString(const s, Old, New: string): string;
  begin
    Result := StringReplace(s, Old, New, [rfReplaceAll]);
  end;

  procedure AddString(Strings: TStringList; s: string);
  begin
    // Ensure we get one line per row by by replacing any cr's & lf's with spaces.
    s := ReplaceString(s, sLineBreak, ' ');
    s := ReplaceString(s, #13, ' ');
    s := ReplaceString(s, #10, ' ');
    Strings.Add(s);
  end;

  function GetHeaderCaptionsAsString: string;
  var
    Col: Integer;
  begin
    Assert(ListView.ViewStyle=vsReport);
    Result := '';
    for Col := 0 to ListView.Columns.Count-1 do begin
      Result := Result + ListView.Columns[Col].Caption;
      if Col<ListView.Columns.Count-1 then begin
        Result := Result + #9;
      end;
    end;
  end;

  function GetItemAsString(Row: Integer): string;
  var
    Index: Integer;
    Item: TListItem;
  begin
    Item := ListView.Items[Row];
    Result := Item.Caption;
    for Index := 0 to Item.SubItems.Count-1 do begin
      Result := Result + #9 + Item.SubItems[Index];
    end;
  end;

var
  Row: Integer;
  OutputAll: Boolean;
  Strings: TStringList;

begin
  Strings := TStringList.Create;
  try
    if ListView.ViewStyle=vsReport then begin
      AddString(Strings, GetHeaderCaptionsAsString);
    end;
    OutputAll := not ListView.MultiSelect or (ListView.SelCount=0);
    for Row := 0 to ListView.Items.Count-1 do begin
      if OutputAll or ListView.Items[Row].Selected then begin
        AddString(Strings, GetItemAsString(Row));
      end;
    end;
    Clipboard.AsText := Strings.Text;
  finally
    FreeAndNil(Strings);
  end;
end;