如何解决如何检测剪贴板文本更改?
剪贴板文本更改时,我的应用程序如何接收通知?
例如:
我将启用/禁用粘贴按钮并设置其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.
解决方法
我找到了一个有趣的PDF arcticle,并使用本文的“使用剪贴板侦听器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 和更早版本,则必须使用剪贴板查看器方法(请参阅前面的“使用剪贴板查看器链” 部分提到了article。另请参见SetClipboardViewer()和Monitoring Clipboard Contents)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。