delphi - 为什么 EN_PROTECT 通知消息没有发送到 RichEdit?

标签 delphi delphi-xe7

使用运行时创建的 TRichEdit 后代,当 EN_PROTECTED 出现时我需要收到通知。通知消息发送到 RichEdit。

据我所知,它应该发送到包含任何可以编辑文本 protected 部分的通知消息的 RichEdit(例如:WM_PASTE),并且原始通知消息代码应该是可在 TWMNotifyRE.ENProtected.msg 中找到。

不幸的是,我的 RichEdit 似乎从未收到 EN_PROTECTED 通知消息。

代码示例:

unit Unit1;

interface

uses
  Vcl.ComCtrls, Winapi.RichEdit, System.UITypes, Vcl.StdCtrls,
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs;

type
  TMyRichEdit = class(Vcl.ComCtrls.TRichEdit)
  private
    procedure CNNotify(var AMessage: TWMNotifyRE); message CN_NOTIFY;
  end;

  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TMyRichEdit.CNNotify(var AMessage: TWMNotifyRE);
begin
  if (AMessage.NMHdr.code = EN_PROTECTED) then
  begin
    //this code is never executed
    DoSometing();
  end else
  begin
    inherited;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  RichEdit : TMyRichEdit;
begin
  RichEdit := TMyRichEdit.Create(Self);
  RichEdit.Align := alClient;
  RichEdit.Parent := Self;
  RichEdit.ScrollBars := ssVertical;
  RichEdit.DefAttributes.Protected := True;
end;

end.

我已经read必须将 DefAttributes.Protected 设置为 True 才能获取 EN_PROTECTED 通知,但这并不能解决问题

最佳答案

问题出在 DefAttributes 实现中。如果其 TRichEdit 控制窗口句柄尚未分配,它将忽略对其进行的任何更改。

要解决这个问题,您可以在更改 DefAttributes 之前强制分配句柄:

RichEdit.HandleNeeded;
RichEdit.DefAttributes.Protected := True;

当您在设计时将 TRichEdit 放在表单上时,设计器会将其 Lines 属性初始化为 'RichEdit1' 或其他值,这从 DFM 加载控件时将导致隐式句柄分配。这可以解释设计者创建的控件行为和手动创建的控件行为之间的差异。

关于delphi - 为什么 EN_PROTECT 通知消息没有发送到 RichEdit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76538721/

相关文章:

delphi - 是否可以有两个同名的属性?

json - TJson.JsonToObject<T> 在多线程环境中抛出错误

windows - JumpList 到 Delphi 上所有打开的表单

delphi - 无法在 XE8 中部署 Ad Hoc Release

delphi - 如何只接受编辑控件中的数字?

delphi - 关于将 SmallInt 与 Ord 函数的结果进行比较的警告

multithreading - DELPHI:多线程客户端/服务器数据快照错误

delphi - 检查变量是否为零的最佳方法?

multithreading - Delphi中两个线程相互同步的最佳方法

json - 如何存储参数化方法的类型参数,然后使用它们将 JSON 对象转换为泛型类型的普通对象?