delphi – 如何从剪贴板粘贴到编辑框中的文本超过最大长度时获取通知?

前端之家收集整理的这篇文章主要介绍了delphi – 如何从剪贴板粘贴到编辑框中的文本超过最大长度时获取通知?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当从剪贴板粘贴到TEdit控件中的文本超过其允许的最大长度时,我需要向用户显示一条消息.但是我不希望每次输入新字母时都要检查程序,只有在粘贴文本时才会检查.

我该怎么做?

解决方法

将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.
原文链接:https://www.f2er.com/delphi/101709.html

猜你在找的Delphi相关文章