How to intercept (detect) a Paste command into a TMemo?

天大地大妈咪最大 提交于 2019-11-30 08:37:14

问题


How to catch Paste command and change text of Clipboard before that text is pasted into a TMemo, but, after Paste, text in Clipboard must be same like before changing?

Example, Clipboard have text 'Simple Question', text that go in the TMemo is 'Симплe Qуeстиoн', and after that text in Clipboard is like before changing, 'Simple Question'.


回答1:


Derive a new control that descends from 'TMemo' to intercept the WM_PASTE message:

type
  TPastelessMemo = class(TMemo)
  protected
    procedure WMPaste(var Message: TWMPaste); message WM_PASTE;
  end;

uses
  clipbrd;

procedure TPastelessMemo.WMPaste(var Message: TWMPaste);
var
  SaveClipboard: string;
begin
  SaveClipboard := Clipboard.AsText;
  Clipboard.AsText := 'Simple Question';
  inherited;
  Clipboard.AsText := SaveClipboard;
end;

If you would like to prohibit any paste operation at all, empty the WMPaste handler.




回答2:


This is an alternative to Sertac's excellent answer, which is to override the control's WndProc:

// For detecting WM_PASTE messages on the control
OriginalMemoWindowProc: TWndMethod;
procedure NewMemoWindowProc(var Message: TMessage);
//...

// In the form's OnCreate procedure:
// Hijack the control's WindowProc in order to detect WM_PASTE messages
OriginalMemoWindowProc := myMemo.WindowProc;
myMemo.WindowProc := NewMemoWindowProc;
//...

procedure TfrmMyForm.NewMemoWindowProc(var Message: TMessage);
var
    bProcessMessage: Boolean;
begin
    bProcessMessage := True;
    if (Message.Msg = WM_PASTE) then
        begin
        // Data pasted into the memo!
        if (SomeCondition) then
            bProcessMessage := False;   // Do not process this message any further!
        end;

    if (bProcessMessage) then
        begin
        // Ensure all (valid) messages are handled!
        OriginalMemoWindowProc(Message);
        end;
end;


来源:https://stackoverflow.com/questions/10158861/how-to-intercept-detect-a-paste-command-into-a-tmemo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!