A subclass of the editing class and listening for the WM_PASTE message . For example (for Unicode Delphi):
uses
Vcl.Clipbrd;
type
TEdit = class(Vcl.StdCtrls.TEdit)
private
procedure WMPaste(var Msg: TWMPaste); message WM_PASTE;
end;
implementation
procedure TEdit.WMPaste(var Msg: TWMPaste);
begin
if (MaxLength > 0) and (Length(Clipboard.AsText) > MaxLength) then
ShowMessage('Text is too long!');
inherited;
end;
Another, slightly more efficient version of WinAPI (which does not copy the clipboard, but simply asks for its size), could be (also for Unicode Delphi):
type
TEdit = class(Vcl.StdCtrls.TEdit)
private
procedure WMPaste(var Msg: TWMPaste); message WM_PASTE;
end;
implementation
procedure TEdit.WMPaste(var Msg: TWMPaste);
var
Data: THandle;
begin
if (MaxLength > 0) and OpenClipboard(0) then
try
Data := GetClipboardData(CF_UNICODETEXT);
if (Data <> 0) and ((GlobalSize(Data) div SizeOf(Char)) - 1 > MaxLength) then
ShowMessage('Text is too long!');
finally
CloseClipboard;
end;
inherited;
end;
If you want the text to not be inserted into the control, remove the inherited calls from the above examples.