2006. október 18., szerda

How to register your own clipboard format


Problem/Question/Abstract:

I want to write raw bytes to the clipboard, but the only functions the TClipboard component offers are SetText, SetAsHandle and SetComponent. Well, I need to set these bytes as a certain format (566 to be exact), so that rules out SetText. SetAsHandle didn't seem to work when I tried it, and I have no idea how SetComponent would do anything for me. The help files included with Delphi (6) weren't overly helpful in explaining how to use this class in any way, other than copying text and pictures.

Answer:

Here is an example:

uses
  Clipbrd;
const
  MyFormatName = 'My Junk Clipboard Format';
  MySource: PChar = 'hello';
var
  MyFormat: Word;
  MySize: Integer;
  MyMemory: THandle;
  MyBuffer: Pointer;
begin
  MyFormat := RegisterClipboardFormat(MyFormatName);
  {Determine the size of the data to be copied.
        StrLen does not count the null terminator.
  So add one byte to be sure it will be pasted correctly as PChar.}
  MySize := StrLen(MySource) + 1;
  {Allocate memory for passing data to the clipboard.}
  MyMemory := GlobalAlloc(GMEM_MOVEABLE, MySize);
  try
    {Copy data to the memory}
    MyBuffer := GlobalLock(MyMemory);
    try
      Move(MySource^, MyBuffer^, MySize);
    finally
      GlobalUnlock(MyMemory);
    end;
    {Call TClipboard.SetAsHandle}
    Clipboard.SetAsHandle(MyFormat, MyMemory);
  except
    GlobalFree(MyMemory);
    raise;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése