【问题标题】:How to get and work with the FONT property of an ANONYMOUS CONTROL?如何获取和使用匿名控件的字体属性?
【发布时间】:2020-12-01 03:13:21
【问题描述】:

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

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 属性,而不必询问类型,然后必须对控件进行类型转换。

但是怎么做呢?

【问题讨论】:

    标签: delphi object-type delphi-10.4-sydney


    【解决方案1】:

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

    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;
    

    【讨论】:

    • 写会不会更好:if System.TypInfo.IsPublishedProp(ThisControl, 'Font') then ThisControl.Font.Size := ThisControl.Font.Size + 1;
    • 不,因为 TCrackControl.Font 总是被发布 - 这就是定义该类并将 TControl 转换为它的全部意义。
    • @AmigoJack:我认为你在这里错了。此方法不会导致发布任何属性。它唯一做的就是使受保护的成员可以访问,因为TCrackControl 是在同一个单元中声明的。 (所以strict protected成员不能通过这种方式访问​​。)
    • 好吧,我可以声明两个控制变量,一个是TControl 类型,一个是TCrackControl 类型。那么代码将是:if System.TypInfo.IsPublishedProp(ThisNoCrackControl, 'Font') then ThisCrackControl.Font.Size := ThisCrackControl.Font.Size + 1;
    • (在任何情况下,A 中都缺少对TCrackControl 的转换。)
    猜你喜欢
    • 1970-01-01
    • 2012-04-12
    • 2013-02-11
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    相关资源
    最近更新 更多