How to get notification when text pasted from clipboard into an edit box exceeds the maximum length?

  • A+
Category:Languages

I need to show a message to the user when text pasted from the clipboard into a TEdit control exceeds its maximum allowed length. But I would not like the program to check every time a new letter is typed, only when text is pasted.

How would I do this?


Subclass the TEdit to handle the EN_MAXTEXT notification:

Sent when the current text insertion has exceeded the specified number of characters for the edit control. The text insertion has been truncated.

This applies to typing as well as pasting, and takes text selection into account for you. For example:

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   TEdit = class(Vcl.StdCtrls.TEdit)   private     procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;   end;    TForm1 = class(TForm)     Edit1: TEdit;   private     { Private declarations }   public     { Public declarations }   end;  var   Form1: TForm1;  implementation  {$R *.dfm}  procedure TEdit.CNCommand(var Message: TWMCommand); begin   inherited;   if Message.NotifyCode = EN_MAXTEXT then     ShowMessage('Too much text!'); end;  end. 

If you only want to handle pasting, then catch WM_PASTE to set a flag before calling inherited, then clear the flag when inherited exits, and if EN_MAXTEXT is issued while the flag is set then act accordingly:

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   TEdit = class(Vcl.StdCtrls.TEdit)   private     FIsPasting: Boolean;     procedure CNCommand(var Message: TWMCommand); message CN_COMMAND;     procedure WMPaste(var Message: TMessage); message WM_PASTE;   end;    TForm1 = class(TForm)     Edit1: TEdit;   private     { Private declarations }   public     { Public declarations }   end;  var   Form1: TForm1;  implementation  {$R *.dfm}  procedure TEdit.CNCommand(var Message: TWMCommand); begin   inherited;   if (Message.NotifyCode = EN_MAXTEXT) and FIsPasting then     ShowMessage('Too much text!'); end;  procedure TEdit.WMPaste(var Message: TMessage); begin   FIsPasting := True;   try      inherited;   finally     FIsPasting := False;   end; end;  end. 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: