2007. szeptember 24., hétfő

How to copy selected items from a TListBox to the clipboard without using the VCL Clipbrd unit


Problem/Question/Abstract:

I want to copy selected items (only text) from a TListBox that has LBS_EXTENDEDSEL style to the standard clipboard using only API functions.

Answer:

This code is untested and requires the unit APIClipboard from Tip "Clipboard access routines which use only API functions".

procedure CopySelectedListboxItemsToClipboard(listboxwnd: HWND);

  function GetItem(num: Integer): string;
  begin
    SetLength(Result, SendMessage(listboxwnd, LB_GETTEXTLEN, num, 0));
    if Length(Result) > 0 then
      SendMessage(listboxwnd, LB_GETTEXT, num, LPARAM(@Result[1]));
  end;

var
  num: Integer;
  selIndices: array of Integer;
  sl: TStringlist;
  S: string;
begin
  num = SendMessage(listboxwnd, LB_GETSELCOUNT, 0, 0);
  if num = LB_ERR then
  begin
    {listbox is a single selection listbox}
    num := SendMessage(listboxwnd, LB_GETCURSEL, 0, 0);
    if num = LB_ERR then
      Exit; {no selected item}
    S := GetItem(num);
  end
  else
  begin
    SetLength(selIndices, num);
    SendMessage(listboxwnd, LB_GETSELITEMS, num, LPARAM(@selIndices[0]));
    sl := TStringlist.Create;
    try
      for num := 0 to High(selIndices) do
        sl.Add(GetItem(selIndices[num]));
      S := sl.Text;
    finally
      sl.free;
    end;
  end;
  StringToClipboard(S);
end;

Nincsenek megjegyzések:

Megjegyzés küldése