将文本从剪贴板保存到文件中



我正在尝试下面的代码,应该保存剪贴板文本到Delphi XE6中的文本文件。代码运行良好,但在输出文件中只生成垃圾值,即使剪贴板包含复制的文本片段也是如此。如何更改代码才能正常工作?

function SaveClipboardTextDataToFile(
  sFileTo : string ) : boolean;
var
  ps1,
  ps2   : PChar;
  dwLen : DWord;
  tf    : TextFile;
  hData : THandle;
begin
  Result := False;
  with Clipboard do
  begin
    try
      Open;
      if( HasFormat( CF_TEXT ) ) then
      begin
        hData :=
          GetClipboardData( CF_TEXT );
        ps1 := GlobalLock( hData );
        dwLen := GlobalSize( hData );
        ps2 := StrAlloc( 1 + dwLen );
        StrLCopy( ps2, ps1, dwLen );
        GlobalUnlock( hData );
        AssignFile( tf, sFileTo );
        ReWrite( tf );
        Write( tf, ps2 );
        CloseFile( tf );
        StrDispose( ps2 );
        Result := True;
      end;
    finally
      Close;
    end;
  end;
end;

您看到的是垃圾,因为CF_TEXT是ANSI。您请求ANSI文本,操作系统将剪贴板内容转换为ANSI,然后将其放入unicode字符串中。在unicode应用程序中使用CF_UNICODETEXT

还要考虑对问题的评论中提出的观点

如果你有Delphi XE6,那么你可以使用一些已经实现的功能

uses
  System.SysUtils,
  System.IOUtils,
  Vcl.Clipbrd;
function SaveClipboardTextDataToFile( const sFileTo : string ) : boolean;
var
  LClipboard : TClipboard;
  LContent : string;
begin
  // get the clipboard content as text
  LClipboard := TClipboard.Create;
  try
    LContent := LClipboard.AsText;
  finally
    LClipboard.Free;
  end;
  // save the text - if any - into a file
  if not LContent.IsEmpty
  then
    begin
      TFile.WriteAllText( sFileTo, LContent );
      Exit( True );
    end;
  Result := False;
end;

最新更新