Recent

Author Topic: Clipboard  (Read 1198 times)

Petrus Vorster

  • Full Member
  • ***
  • Posts: 249
Clipboard
« on: July 31, 2025, 10:16:38 am »
Hi All

I get updated box numbers via an Excel file.
I have made a listbox to copy and paste the Excel column with the box numbers.

The copy and paste parts works well, but it paste it as one long string and not individual numbers one below the other.
I assume the Crlf is not handled or there is just something i need to set.

Code: Pascal  [Select][+][-]
  1. procedure TMainform.MenuItem1Click(Sender: TObject);
  2. var
  3.   Tclip:tclipboard;
  4. begin
  5.   listbox1.Items.Clear;
  6.   if Clipboard.HasFormat(CF_TEXT) then
  7.   listbox1.Items.Add(Clipboard.AsText);
  8.  
  9. end;            

Some ideas would be much appreciated.

-Peter

Petrus Vorster

  • Full Member
  • ***
  • Posts: 249
Re: Clipboard
« Reply #1 on: July 31, 2025, 10:30:16 am »
Ok, this seem to work:
Code: Pascal  [Select][+][-]
  1. procedure TMainform.MenuItem1Click(Sender: TObject);
  2. var
  3.   PastedText: string;
  4.   Lines: TStringList;
  5.   i: Integer;
  6. begin
  7.   // 1. Retrieve Pasted Text
  8.   PastedText := Clipboard.AsText;
  9.  
  10.   // 2. Split Text into Lines
  11.   Lines := TStringList.Create;
  12.   try
  13.     Lines.Text := PastedText; // TStringList automatically splits by line breaks
  14.  
  15.     // 3. Add Lines to ListBox
  16.     for i := 0 to Lines.Count - 1 do
  17.     begin
  18.       ListBox1.Items.Add(Lines[i]);
  19.     end;
  20.   finally
  21.     Lines.Free;
  22.   end;
  23. end;                

Unless someone has some better examples.

-Peter

Thaddy

  • Hero Member
  • *****
  • Posts: 19455
  • Glad to be alive.
Re: Clipboard
« Reply #2 on: July 31, 2025, 12:50:40 pm »
Listbox.Items is also a Tstrings descendant, just like TStringlist, so
Code: Pascal  [Select][+][-]
  1.    
  2.    // 3. Add Lines to ListBox  
  3.    ListBox1.Items.Assign(Lines);
  4.  
No for-to loop needed.

Even better:
Code: Pascal  [Select][+][-]
  1.     Listbox1.items.text := PastedText; // TStrings automatically splits by line breaks
  2.  
No stringlist needed either.

And even one bettered:
Code: Pascal  [Select][+][-]
  1.     Listbox1.items.text := Clipboard.AsText;// TStrings automatically splits by line breaks
  2.  
No variables needed at all
All because of the beauty of TStrings abstraction and OOP.

So now we have:
Code: Pascal  [Select][+][-]
  1. procedure TMainform.MenuItem1Click(Sender: TObject);
  2. begin
  3.   if Clipboard.HasFormat(CF_TEXT) then
  4.     ListBox1.Items.text := Clipboard.AsText;
  5. end;

I suggest you use the last one.....

« Last Edit: July 31, 2025, 04:41:04 pm by Thaddy »
Any "programmer" that knows only one programming language is not a programmer

Petrus Vorster

  • Full Member
  • ***
  • Posts: 249
Re: Clipboard
« Reply #3 on: August 01, 2025, 09:15:45 am »
Wow.

Great stuff.
Thanks a million.

-Peter

 

TinyPortal © 2005-2018