解决方法
将TEdit子类化以处理
EN_MAXTEXT
通知:
Sent when the current text insertion has exceeded the specified number of characters for the edit control. The text insertion has been truncated.
这适用于键入和粘贴,并为您考虑文本选择.例如:
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.
如果您只想处理粘贴,则在调用inherited之前捕获WM_PASTE以设置标志,然后在继承退出时清除该标志,并且如果在设置该标志时发出EN_MAXTEXT,则相应地执行:
unit Unit1; interface uses Winapi.Windows,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.