首页 > 解决方案 > 如何检测剪贴板文本更改?

问题描述

当剪贴板文本更改时,我的应用程序如何接收通知?

例如:

我会启用/禁用粘贴按钮并设置其Hint属性以显示剪贴板的文本(如'Paste "%s"'

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TMyPasteForm = class(TForm)
    MyPasteButton: TButton;
    MyEdit: TEdit;
    procedure MyPasteButtonClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    procedure SyncMyPasteButton();
    { Private declarations }
  public
    { Public declarations }
  end;

var
  MyPasteForm: TMyPasteForm;

implementation

{$R *.dfm}

uses
  Clipbrd;

procedure TMyPasteForm.FormCreate(Sender: TObject);
begin
  MyPasteButton.ShowHint := True;
end;

procedure TMyPasteForm.MyPasteButtonClick(Sender: TObject);
begin
  MyEdit.Text := Clipboard.AsText;
end;

procedure TMyPasteForm.SyncMyPasteButton();
begin
  MyPasteButton.Enabled := Length(Clipboard.AsText) > 0;
  MyPasteButton.Hint := Format('Paste "%s"', [Clipboard.AsText]);
end;

end.

标签: delphiclipboarddelphi-xe7

解决方案


我找到了一个有趣的PDF 文章,并在文章的“使用剪贴板侦听器 API”部分相应地编辑了我的示例:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TMyPasteForm = class(TForm)
    MyPasteButton: TButton;
    MyEdit: TEdit;
    procedure MyPasteButtonClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    procedure SyncMyPasteButton();
    procedure WMClipboardUpdate(var Msg : TMessage); message WM_CLIPBOARDUPDATE;
  protected
    procedure CreateWnd(); override;
    procedure DestroyWnd(); override;
  public
    { Public declarations }
  end;

var
  MyPasteForm: TMyPasteForm;

implementation

{$R *.dfm}

uses
  Clipbrd;

procedure TMyPasteForm.FormCreate(Sender: TObject);
begin
  MyPasteButton.ShowHint := True;

  SyncMyPasteButton();
end;

procedure TMyPasteForm.CreateWnd();
begin
  inherited;
  //making sure OS notify this window when clipboard content changes
  AddClipboardFormatListener(Handle);
end;

procedure TMyPasteForm.DestroyWnd();
begin
  //remove the clipboard listener
  RemoveClipboardFormatListener(Handle);
  inherited;
end;

procedure TMyPasteForm.MyPasteButtonClick(Sender: TObject);
begin
  MyEdit.Text := Clipboard.AsText;
end;

procedure TMyPasteForm.SyncMyPasteButton();
begin
  MyPasteButton.Enabled := IsClipboardFormatAvailable(CF_TEXT);

  if(MyPasteButton.Enabled) then
    MyPasteButton.Hint := Format('Paste "%s"', [Clipboard.AsText])
  else
    MyPasteButton.Hint := '';
end;

procedure TMyPasteForm.WMClipboardUpdate(var Msg : TMessage);
begin
  //the clipboard content is changed!
  SyncMyPasteButton();
end;

end.

笔记:

  • 它适用于Windows Vista及更高版本。

  • 如果您需要支持Windows XP和更早版本,则必须使用剪贴板查看器方法(请参阅前面提到的文章的“使用剪贴板查看器链”部分。另请参阅SetClipboardViewer()监视剪贴板内容


推荐阅读