Author: Tomas Rutkauskas
How to create a panel which resizes itself and all components on it at runtime
Answer:
Here's the source code for a resizable panel. Give the panel an align property of
alClient, throw some controls on it, and watch them resize at run time when you
resize the form. There is some code that prohibits resizing during design time, but
this can be taken out.
1 unit Elastic;
2
3 interface
4
5 uses
6 SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms,
7 Dialogs, ExtCtrls;
8
9 type
10 TElasticPanel = class(TPanel)
11 private
12 FHorz, FVert: boolean;
13 nOldWidth, nOldHeight: integer;
14 bResized: boolean;
15 protected
16 procedure WMSize(var message: TWMSize); message WM_SIZE;
17 public
18 nCount: integer;
19 constructor Create(AOwner: TComponent); override;
20 published
21 property ElasticHorizontal: boolean read FHorz write FHorz default True;
22 property ElasticVertical: boolean read FVert write FVert default True;
23 end;
24
25 procedure register;
26
27 implementation
28
29 constructor TElasticPanel.Create(AOwner: TComponent);
30 begin
31 inherited Create(AOwner);
32 FHorz := True;
33 FVert := True;
34 nOldWidth := Width;
35 nOldHeight := Height;
36 bResized := False;
37 end;
38
39 procedure TElasticPanel.WMSize(var message: TWMSize);
40 var
41 bResize: boolean;
42 xRatio: real;
43 i: integer;
44 ctl: TWinControl;
45 begin
46 Inc(nCount);
47 if Align = alNone then
48 bResize := TRUE
49 else
50 bResize := bResized;
51 if not (csDesigning in ComponentState) and bResize then
52 begin
53 if FHorz then
54 begin
55 xRatio := Width / nOldWidth;
56 for i := 0 to ControlCount - 1 do
57 begin
58 ctl := TWinControl(Controls[i]);
59 ctl.Left := Round(ctl.Left * xRatio);
60 ctl.Width := Round(ctl.Width * xRatio);
61 end;
62 end;
63 if FVert then
64 begin
65 xRatio := Height / nOldHeight;
66 for i := 0 to ControlCount - 1 do
67 begin
68 ctl := TWinControl(Controls[i]);
69 ctl.Top := Round(ctl.Top * xRatio);
70 ctl.Height := Round(ctl.Height * xRatio);
71 end;
72 end;
73 end
74 else
75 begin
76 nOldWidth := Width;
77 nOldHeight := Height;
78 end;
79 bResized := TRUE;
80 nOldWidth := Width;
81 nOldHeight := Height;
82 end;
83
84 procedure register;
85 begin
86 RegisterComponents('Additional', [TElasticPanel]);
87 end;
88
89 end.
|