Using Clipboard in Delphi FMX apps

In Delphi FMX multi-platforms apps, you can use the system clipboard (on Windows, Linux, MacOS, iOS and Android) to copy and paste data like text and images.

There is two options in Delphi FMX, you can use :

  • FMX.Platform.IFMXClipboardService : a clipboard service in the FMX.Platform unit, it has basic methods for copy/paste a TValue.
  • FMX.Clipboard.IFMXExtendedClipboardService : a more advanced clipboard service in the FMX.Clipboard unit, it has advanced methods for registering/unregistering a custom format contents and detecting the clipboard contents type if it is a text or image.

Both of these options are platform-specific service’s interfaces, the FMX app can not directly access the clipboard.

The implementation’s code (like for any FMX platform services) must be a condition to ask the platform whether it actually support the clipboard feature, then your app will get the service interface (using the function : TPlatformServices.Current.SupportsPlatformService) and use it.

FMX.Platform.IFMXClipboardService

In the uses clauses, you need to add just the FMX.Platform unit :

uses
...
FMX.Platform,
...

And put this code in your routine (AValue can be any kind of data value of a variable, a constant or a control’s property : string, bitmap, text or bitmap properties of a control, etc.) :

var
uClipBoard : IFMXClipboardService;

begin
if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, uClipBoard)
then uClipBoard.SetClipboard(AValue);
end;

FMX.Clipboard.IFMXExtendedClipboardService

In the uses clauses, you must add this two units :

uses
...
FMX.Platform, FMX.Clipboard, 
...

And put this code in your routine (AValue can be any kind of data value or property : a string, a bitmap, text or bitmap properties of a control, etc.) :

var
uClipBoard : IFMXExtendedClipboardService;

begin
if TPlatformServices.Current.SupportsPlatformService(IFMXExtendedClipboardService, uClipBoard)
then uClipBoard.SetClipboard(AValue);
end;

Get data from clipboard

You can get and use the new data from clipboard using the paste command in your platform.

Or, inside your app on runtime, by calling the GetClipboard function. This call must be in a condition to prevent errors and unexpected responses.

This is an example for string data, you can

var
  uClipBoard : IFMXClipboardService;
  Value : TValue;
  Text : string;

begin
if TPlatformServices.Current.SupportsPlatformService(IFMXClipboardService, uClipBoard) then 
   begin
   Value := uClipBoard.GetClipboard;
   if not Value.IsEmpty
   and Value.TryAsType(Text) 
      then Text := Value.ToString
      else Text := '';
   end;

// Insert some code here to use the Text variable's value in a control's text property or in another string variable 

end;

See also

Leave a Reply