1

在 Delphi 10.4 中,在 VCL 应用程序中,使用组件的OnMessage事件处理程序TApplicationEvents,我增加了右键单击控件的字体大小:

procedure TformMain.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
var
  ThisControl: TControl;
begin
  if (Msg.Message = WM_RBUTTONDOWN) then
  begin
    ThisControl := FindDragTarget(Mouse.CursorPos, True);
    CodeSite.Send('TformMain.ApplicationEvents1Message: RIGHTCLICK!', ThisControl.Name);
    if ThisControl is TLabel then
      TLabel(ThisControl).Font.Size := TLabel(ThisControl).Font.Size + 1
    else if ThisControl is TCheckBox then
      TCheckBox(ThisControl).Font.Size := TCheckBox(ThisControl).Font.Size + 1;
    // ETC. ETC. ETC.! :-(
  end;
end;

这是一种非常低效的方法来使所有控件类型都可以使用,因为我必须枚举所有现有的控件类型,因为TControl没有TFont属性。

更好的方法是获取TFont控件的属性,而不必询问类型,然后必须对控件进行 TYPECAST。

但是如何?

4

1 回答 1

2

如果您重新声明类型,您可以访问该类的受保护属性。现在你用一个插入器类来做到这一点,但我仍然习惯于旧的方式。当您对字体执行某些操作时,您可能必须添加一个检查,如果事实证明某个特定的控件炸弹。到目前为止,它一直对我有用。

type
  TCrackControl = class(TControl);

procedure TformMain.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
var
  ThisControl: TCrackControl;
begin
  if (Msg.Message = WM_RBUTTONDOWN) then
  begin
    ThisControl := TCrackControl(FindDragTarget(Mouse.CursorPos, True));
    CodeSite.Send('TformMain.ApplicationEvents1Message: RIGHTCLICK!', ThisControl.Name);
    If assigned(ThisControl.Font) then
    ThisControl.Font.Size := ThisControl.Font.Size + 1;
   
  end;
end;
于 2020-08-11T13:28:48.313 回答