我想创建一个从 TPanel 派生的自定义控件,其中包含一个图像和一堆其他控件。编写代码后,我的程序中有一些奇怪的行为。我意识到一些应该在 TDisplay.Resize (覆盖)中初始化的变量从未被初始化,因为 Resize 从未被执行。
为了“解决它”,我在表单上放了一个按钮并调用了 LoadSample 函数,该函数调用了 ClientHeight,该函数第一次调用了 Resize!
constructor TDisplay.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Ready := FALSE;
Parent := Owner as TWinControl;
Width := 200;
Height := 86;
Color := clSilver;
Caption := '';
DoubleBuffered:= TRUE;
InternalDisplay:= TImage32.Create(Self);
with Display DO
begin
Parent := Self;
Bitmap.Width := 1;
Bitmap.Height := 1;
RepaintMode := rmOptimizer;
Align := alClient;
SetupBitmap(TRUE, clBlack32);
Visible := TRUE;
OnMouseDown := DMouseDown;
end;
...
end;
更新:
在我在运行时手动调整表单(控件)的大小之前,InternalDisplay 也不会与其父大小对齐。只有这样,它才会按预期的方式运行(与 alClient 保持一致)。
更新 2:
Resize 声明如下:procedure Resize; 覆盖;
更新 3:
我从构造函数中删除了 ClientHeight 行并将其移至此处:
procedure TDisplay.LoadSample(VAR Obj: TMySample; CONST bReleaseOnExit: boolean)
begin
ClientHeight; <--------- this will call Resize for the first time and my code will be finally initialized. But until this point my display will look odd because the code was never initialized. So the user will see weird stuff until it pushes the 'LoadSample' button.
more code here....
end;
更新 4:
我按照 David 的建议使用了 HandleNeeded,它解决了初始化问题。但是,除非我手动调整表单/控件的大小,否则图像仍然不会与整个客户区对齐。
更新 5
在这里继续,正如 David 所建议的那样:TImage 不会与父级对齐