Copy ANSI Text To Clipboard - Delphi

DarkCoderSc personal avatar
DarkCoderSc

Jean-Pierre LESUEUR

procedure CopyToClipboard(const AString : AnsiString);
begin
  if not OpenClipboard(0) then
    raise EWindowsException.Create('OpenClipboard');
  try
    if not EmptyClipboard() then
      raise EWindowsException.Create('EmptyClipboard');

    var ADataLength := Length(AString)+1;
    var hMem := GlobalAlloc(GMEM_MOVEABLE, ADataLength);
    try
      var pMem := GlobalLock(hMem);
      try
        CopyMemory(pMem, PAnsiChar(AString), ADataLength);

        ///
        if SetClipboardData(CF_TEXT, hMem) = 0 then
          raise EWindowsException.Create('SetClipboardData');
      finally
        GlobalUnlock(hMem);
      end;
    finally
      GlobalFree(hMem);
    end;
  finally
    CloseClipboard();
  end;
end;

Creating and researching code snippets takes time and effort. You’re welcome to share them through your own platforms, but please don’t forget to credit the original author, here: Jean-Pierre LESUEUR.

Depends On


Created

May 9, 2025

Last Revised

May 14, 2025