按照此处的示例http://www.tek-tips.com/faqs.cfm?fid=6272我修改了组件,以便在TRichEdit中检测OnPaste事件。以下是源代码:
type
TStringEvent = procedure(Sender: TObject; var s: String) of object;
TRichEditEx = class(TRichEdit)
private
FOnBeforePaste: TStringEvent;
FOnAfterPaste: TNotifyEvent;
procedure WMPaste(var Message: TMessage); message WM_PASTE;
protected
public
published
property OnBeforePaste: TStringEvent read FOnBeforePaste write FOnBeforePaste;
property OnAfterPaste: TNotifyEvent read FOnAfterPaste write FOnAfterPaste;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('.....', [TRichEditEx]);
end;
{ TRichEditEx }
procedure TRichEditEx.WMPaste(var Message: TMessage);
var
strClpText: String;
begin
// Check if the OnBeforePaste event is assigned and check if the clipboard contains plain text.
if Assigned(FOnBeforePaste) and Clipboard.HasFormat(CF_TEXT) then
begin
// Save the clipboard text into a local variable
strClpText := ClipBoard.AsText;
// Fire the OnBeforePaste event
FOnBeforePaste(self, strClpText);
// Clear the clipboard and replace it with the new text
Clipboard.Clear;
Clipboard.AsText := strClpText;
end;
// Perform the actual paste
inherited;
// if the OnAfterPaste event is assigned, fire it.
if Assigned(FOnAfterPaste) then
FOnAfterPaste(self);
end;
end.
我成功注册了该组件,但没有触发这两个事件。
我在这里做错了什么?
修改
受到TLama解决方案的启发,我使用了另一种方法并覆盖了 WM_KeyDown 。以下是代码:
TRichEditBeforePasteEvent = procedure(Sender: TObject; var Content: string; var CanPaste: Boolean) of object;
TRichEditEx = class(Vcl.ComCtrls.TRichEdit)
private
FOnAfterPaste: TNotifyEvent;
FOnBeforePaste: TRichEditBeforePasteEvent;
protected
procedure WM_KeyDown(var Msg: TWMKeyDown); message WM_KEYDOWN;
public
constructor Create(AOwner: TComponent); override;
published
property OnAfterPaste: TNotifyEvent read FOnAfterPaste write FOnAfterPaste;
property OnBeforePaste: TRichEditBeforePasteEvent read FOnBeforePaste write FOnBeforePaste;
end;
constructor TRichEditEx.Create(AOwner: TComponent);
begin
inherited;
Self.DefAttributes.Protected := True;
end;
procedure TRichEditEx.WM_KeyDown(var Msg: TWMKeyDown);
var
ShiftState: TShiftState;
Content: string;
CanPaste: Boolean;
begin
if PlainText then begin
ShiftState := KeyDataToShiftState(Msg.KeyData);
if (ssCtrl in ShiftState) and
(Msg.CharCode = Ord('V')) then
begin
CanPaste:=True;
if Assigned(FOnBeforePaste) then
begin
Content := Clipboard.AsText;
FOnBeforePaste(Self, Content, CanPaste);
Clipboard.AsText:=Content;
end;
if CanPaste then begin
self.PasteFromClipboard;
if Assigned(FOnAfterPaste) then
FOnAfterPaste(Self);
end
end
else
inherited;
end
else
inherited;
end;
到目前为止它对我有用。