Author: Tomas Rutkauskas
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".
1
2 procedure CopySelectedListboxItemsToClipboard(listboxwnd: HWND);
3
4 function GetItem(num: Integer): string;
5 begin
6 SetLength(Result, SendMessage(listboxwnd, LB_GETTEXTLEN, num, 0));
7 if Length(Result) > 0 then
8 SendMessage(listboxwnd, LB_GETTEXT, num, LPARAM(@Result[1]));
9 end;
10
11 var
12 num: Integer;
13 selIndices: array of Integer;
14 sl: TStringlist;
15 S: string;
16 begin
17 num = SendMessage(listboxwnd, LB_GETSELCOUNT, 0, 0);
18 if num = LB_ERR then
19 begin
20 {listbox is a single selection listbox}
21 num := SendMessage(listboxwnd, LB_GETCURSEL, 0, 0);
22 if num = LB_ERR then
23 Exit; {no selected item}
24 S := GetItem(num);
25 end
26 else
27 begin
28 SetLength(selIndices, num);
29 SendMessage(listboxwnd, LB_GETSELITEMS, num, LPARAM(@selIndices[0]));
30 sl := TStringlist.Create;
31 try
32 for num := 0 to High(selIndices) do
33 sl.Add(GetItem(selIndices[num]));
34 S := sl.Text;
35 finally
36 sl.free;
37 end;
38 end;
39 StringToClipboard(S);
40 end;
|