问题描述
在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
属性,而无需询问TYPE,然后必须对控件进行TYPECAST。
但是如何?
解决方法
如果重新声明类型,则可以访问该类的受保护属性。 如今,您可以使用中介层类来完成此操作,但是我仍然习惯于旧方法。 当您对字体进行某些操作时,如果事实证明是特定的控制炸弹,则可能必须添加检查。到目前为止,它一直对我有用。
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;