Как изменить размер формы delphi

Изменение размеров формы Delphi Решение и ответ на вопрос 749316
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
unit Unit1;
 
interface
 
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls, XPMan, Menus, jpeg, ExtCtrls, Grids, Math,
  MPlayer, TeEngine, Series, TeeProcs, Chart, ActnList,  WMPLib_TLB,
  OleCtrls;
 
type
  TForm1 = class(TForm)
    pgc1: TPageControl;
    ts1: TTabSheet;
    ts2: TTabSheet;
    ts3: TTabSheet;
    ts4: TTabSheet;
    mm1: TMainMenu;
    N1: TMenuItem;
    N2: TMenuItem;
    lbl5: TLabel;
    edt3: TEdit;
    Label1: TLabel;
    StringGrid1: TStringGrid;
    Chart1: TChart;
    Series1: TLineSeries;
    Chart2: TChart;
    Series2: TLineSeries;
    Button2: TButton;
    grp2: TGroupBox;
    lbl6: TLabel;
    edt1: TEdit;
    edt2: TEdit;
    img3: TImage;
    img4: TImage;
    Edit5: TEdit;
    img5: TImage;
    img1: TImage;
    img2: TImage;
    wndwsmdplyr1: TWindowsMediaPlayer;
    procedure FormResize(Sender: TObject);
    procedure FormCanResize(Sender: TObject; var NewWidth,
      NewHeight: Integer; var Resize: Boolean);
    procedure FormCreate(Sender: TObject);
    procedure btn2Click(Sender: TObject);
    procedure img4Click(Sender: TObject);
 
 
 
 
 
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form1: TForm1;
  tabl1: array[1..3, 1..41] of  String;
  SGColStr: Integer;
  tos: Extended;
 
implementation
 
{$R *.dfm}
 
procedure TForm1.FormResize(Sender: TObject);
begin
  pgc1.Height:=Form1.Height-56;
      pgc1.Width:=Form1.Width-15;
      ts1.Width:=pgc1.Width-12;
       ts1.Height:=pgc1.Height-30;
       img5.Width:=pgc1.Width-12;
       img5.Height:=pgc1.Height-30;
       img3.Width:=pgc1.Width-12;
       img3.Height:=pgc1.Height-30;
 
end;
 
 
 procedure TForm1.FormCanResize(Sender: TObject; var NewWidth,
  NewHeight: Integer; var Resize: Boolean);
begin
 
     img1.Height:=ts2.Height-100;
      img1.Width:=ts2.Width-100;
      img2.Height:=ts2.Height-100;
      img2.Width:=ts2.Width-100;
end;
 
 
procedure TForm1.FormCreate(Sender: TObject);
var dir : string;
begin
 
   
wndwsmdplyr1.uiMode := 'none';
 wndwsmdplyr1.Width := 320;
 wndwsmdplyr1.Height := 240;
 
  
   Randomize;
   tos := Random(31) + 10;
   Edit5.text := FloatToStr(tos);
 
  
       With Stringgrid1 Do begin
       Cells[0,0] := '¹ ï/ï';
       Cells[1,0] := 'I, A';
       Cells[2,0] := 'U, Â';
       Cells[3,0] := 'Tc, 0Ñ';
       Cells[4,0] := 'q, Âò/ì2';
       Cells[5,0] := 'qè, Âò/ì2';
       Cells[6,0] := 'qê, Âò/ì2';
       Cells[7,0] := 'a, Âò/ì2Ñ';
       Cells[8,0] := 'Nu';
       Cells[9,0] := 'Gr';
       Cells[10,0] := 'lnNu';
       Cells[11,0] := 'lnGr';
       Cells[12,0] := 'GrPr';
       Cells[13,0] := 'lnGrPr';
 
   End;
 
       tabl1[1,1] := '46.86';
      .....
 
       tabl1[3,41] := '329.87';
 
 
       SGColStr := 0;
end;

I have an application that has 5 different sized frames. I’d like to dynamically re-size the main form to fit the frame when I move from one frame to another.

I can use the MinHeight/MinWidth properties of the frame to force the main form to fit the frame, but then when moving to a smaller frame, the main form does not adjust it’s size.

Any ideas?

—Edit

...
TFormMain = Class(TForm)
...
public
  FrameImportPackage: TFrameImportPackage;
...

procedure TFormMain.MenuPackagesImportClick(Sender: TObject);
begin
  if not (Assigned(FrameImportPackage)) then
    begin
      FrameImportPackage := TFrameImportPackage.Create(Self);
      FrameImportPackage.LabelFrameCaption.Caption := 'Import or Edit a Package';
    end
  else
    begin
      FrameImportPackage.BringToFront;
    end;

  FrameImportPackage.Parent := Self;
end;

—Edit

Regards, Pieter

asked Jul 15, 2011 at 8:54

Pieter van Wyk's user avatar

Pieter van WykPieter van Wyk

2,3069 gold badges46 silver badges65 bronze badges

6

If I understand your question correctly, you’ve got frames that don’t change size, you want the form to update size to fit your frames. Let Delphi handle that for you, using the AutoSize property.

Set AutoSize = True for your form.


I’ve tested AutoSize with the following code, using Delphi 2010:

  • Create a new VCL application. On the blank form drop a single Panel, let it keep it’s name (Panel1). Make sure the panel is not too small, because we’ll write code to decrease it’s size at runtime.
  • Set the form’s AutoSize property to True.
  • Drop two buttons on the panel, Button1 and Button2.
  • Double click the buttons, and copy-paste the following event handlers:

Code:

procedure TForm31.Button1Click(Sender: TObject);
var NewR: TRect;
begin
  NewR := Panel1.BoundsRect;
  Dec(NewR.Right, 32);
  Dec(NewR.Bottom, 32);

  Button1.Parent := Self;
  Button2.Parent := Self;

  Panel1.Free;
  Panel1 := TPanel.Create(Self);
  Panel1.BoundsRect := NewR;
  Panel1.Parent := Self;

  Button1.Parent := Panel1;
  Button2.Parent := Panel1;
end;

procedure TForm31.Button2Click(Sender: TObject);
begin
  Panel1.Height := Panel1.Height - 32;
  Panel1.Width := Panel1.Width - 32;
end;

This essentially gives you two ways of decreasing the size of the panel, to handle two possible scenarios: Button1 frees the old panel and creates a new, smaller panel. Button2 directly resize the existing panel. Both work as expected!

answered Jul 15, 2011 at 8:58

Cosmin Prund's user avatar

Cosmin PrundCosmin Prund

25.4k2 gold badges59 silver badges104 bronze badges

4

At least on Delphi 2006 there is a really anonying BUG with Form AutoSize.

You put a TStringGrid onto the form (Left and Top equal zero, align equal None, Top, CLient does not matter), when you change its ClientWidth and ClientHeightt the form not allways adjusts its size to the control.

Normally when it fails is when control size is reduced, form size does not get reduced.

There is no good fix, the only way to do it is manually set clientwidth and clientheight of the form when the object is resized.

It is said: Form AutoSize does not allways work well! It is a BUG on the VCL.

answered Mar 23, 2017 at 11:16

claudio's user avatar

I have a Window, in which i display a picture. I want the user to be able to resize this window, but
keep it in the same aspect ratio than the image, so no big empty areas appear on the window.

What i tried is something like this in the OnResize event:

DragWidth := Width;
DragHeight := Height;

//Calculate corresponding size with aspect ratio
//...
//Calculated values are now in CalcWidth and CalcHeight

Width := CalcWidth;
Height := CalcHeight;

The Problem with this is, that the window flashes during the resize dragging between the original resize size and the calculated, since the OnResize event is afaik called after the resize is already done (and painted once).

Do you know any solution for having a smooth aspect-ratio resizing?

Thanks for any Help.

asked Jun 7, 2011 at 13:15

Marks's user avatar

Adding the following handler for the OnCanResize event seemed to work very well for me:

procedure TForm1.FormCanResize(Sender: TObject; var NewWidth,
  NewHeight: Integer; var Resize: Boolean);
var
  AspectRatio:double;
begin
  AspectRatio:=Height/Width;
  NewHeight:=round(AspectRatio*NewWidth);
end;

You may of course want to change the method for calculating NewHeight and NewWidth. The following method feels intuitively «right» when I try it on a blank form:

  NewHeight:=round(0.5*(NewHeight+AspectRatio*NewWidth));
  NewWidth:=round(NewHeight/AspectRatio);

answered Jun 7, 2011 at 13:40

boileau's user avatar

boileauboileau

8076 silver badges19 bronze badges

5

Recent delphi’s have the OnCanResize event, that allow you to do exactly this. You can simply return the calculated NewWidth and NewHeight directly from the event.

answered Jun 7, 2011 at 13:36

Paul-Jan's user avatar

Paul-JanPaul-Jan

16.7k1 gold badge63 silver badges94 bronze badges

I have a Window, in which i display a picture. I want the user to be able to resize this window, but
keep it in the same aspect ratio than the image, so no big empty areas appear on the window.

What i tried is something like this in the OnResize event:

DragWidth := Width;
DragHeight := Height;

//Calculate corresponding size with aspect ratio
//...
//Calculated values are now in CalcWidth and CalcHeight

Width := CalcWidth;
Height := CalcHeight;

The Problem with this is, that the window flashes during the resize dragging between the original resize size and the calculated, since the OnResize event is afaik called after the resize is already done (and painted once).

Do you know any solution for having a smooth aspect-ratio resizing?

Thanks for any Help.

asked Jun 7, 2011 at 13:15

Marks's user avatar

Adding the following handler for the OnCanResize event seemed to work very well for me:

procedure TForm1.FormCanResize(Sender: TObject; var NewWidth,
  NewHeight: Integer; var Resize: Boolean);
var
  AspectRatio:double;
begin
  AspectRatio:=Height/Width;
  NewHeight:=round(AspectRatio*NewWidth);
end;

You may of course want to change the method for calculating NewHeight and NewWidth. The following method feels intuitively «right» when I try it on a blank form:

  NewHeight:=round(0.5*(NewHeight+AspectRatio*NewWidth));
  NewWidth:=round(NewHeight/AspectRatio);

answered Jun 7, 2011 at 13:40

boileau's user avatar

boileauboileau

8076 silver badges19 bronze badges

5

Recent delphi’s have the OnCanResize event, that allow you to do exactly this. You can simply return the calculated NewWidth and NewHeight directly from the event.

answered Jun 7, 2011 at 13:36

Paul-Jan's user avatar

Paul-JanPaul-Jan

16.7k1 gold badge63 silver badges94 bronze badges

 
Micah’GF
 
(2002-08-31 22:39)
[0]

Как изменить размер формы? А то меньше 114 по ширине не получается.


 
CrazyAngel
 
(2002-08-31 23:00)
[1]

А у меня получилось только видно ето в runtime

в designtime действительно не получается


 
Micah’GF
 
(2002-09-01 08:54)
[2]

Как понять в рантайм? Напиши поподробнее!

А можно как нибудь после старта приложения уменьшить размер?


 
alena.svt
 
(2002-09-01 10:24)
[3]

В событии OnCreate для формы пишишь

Form1.Height:= 100;

Form1.Width:= 114;


 
alena.svt
 
(2002-09-01 11:17)
[4]

Если форма со стилем bsSizable то не получиться, только при bsDialog

А если нужна иконка и кнонки то можно имитировать лишив сначала форму caption»a и сделав его например из панельки.


 
MsGuns
 
(2002-09-01 13:18)
[5]

>alena.svt © (01.09.02 10:24)

>В событии OnCreate для формы пишишь

>Form1.Height:= 100;

>Form1.Width:= 114;

>alena.svt © (01.09.02 11:17)

>Если форма со стилем bsSizable то не получиться, только при >bsDialog

— Нужели ?


 
alena.svt
 
(2002-09-01 13:30)
[6]

>MsGuns © — Нужели ?

Что означает простите за серость?


 
Micah’GF
 
(2002-09-01 21:36)
[7]

Пасибо alena.svt! Все получилось как ты говорила, тока у меня BorderStile = bsNone, но все нормально.


 
Micah’GF
 
(2002-09-01 21:44)
[8]

А вот тут вот сразу еще один вопросик появился. Надо эту формочку поместить в правый верхний угол. А то я делаю alCustom и вручную ставлю ее в угол, а при изменении разрешения форма оставляет прежнее положение.


 
alena.svt
 
(2002-09-01 22:12)
[9]

Я не поняла зачем bsNone только конечно это вам нужно

Можно и bsSiziable но без Сaption»a(не надписи а заголока)или bsSingle если вам ее растягивать ее нельзя.

В событии OnCreate для формы



procedure TForm1.FormCreate(Sender: TObject);

var

FSizeCaption : Integer;

begin

FSizeCaption := GetSystemMetrics(SM_CYCAPTION);

SetWindowLong(Form1.Handle, GWL_STYLE, GetWindowLong(Form1.Handle, GWL_Style) and not WS_Caption);

Form1.Height:=Form1.Height - FSizeCaption;

end;



А по второму незнаю это через TScreen наверное делается, но чтоб отследить когда юзер поменял разрешение экрана???


 
Malder
 
(2002-09-01 22:58)
[10]

>Надо эту формочку поместить в правый верхний угол

procedure TForm1.FormCreate(Sender: TObject);

begin

Form1.top:=0;

Form1.left:=Screen.Width-Form1.Width;

end;


 
alena.svt
 
(2002-09-01 23:04)
[11]

>Malder ©

В правый верхнии угол можно и Align alRight

Только MaxWidth и MaxHeight установить.

А вот как ему отследить когда разрешение меняется.


 
Bass1
 
(2002-09-02 11:54)
[12]

Screen.width ???

Лучше monitor.workarea.top и monitor.workarea.right-form1.width тогда не будет зависеть от разрешения и всяких там таскбаров и других панелей.


 
MBo
 
(2002-09-02 12:05)
[13]

http://www.swissdelphicenter.ch/en/showcode.php?id=1063


 
Micah’GF
 
(2002-09-03 08:29)
[14]

2alena.svt

>Я не поняла зачем bsNone только конечно это вам нужно

Да все нормально! Формочка представляет собой как бу просто картинку. Она не имеет заголовка с кнопочками закрыть,… (это просто не нужно), все что нужно нарисовано на картинке.

А вообще всем спасибо… помогли хорошо. А насчет положения формы: она устанавливается в угол перечисленными способами, а при смене разрешения на большее немного сдвигается влево относительно правого края экрана гдето примерно 4-5 точек. При смене на меньшее — всё нормально.


  Пришло время погрузиться в практическую часть и в этом уроке мы рассмотрим форму и ее основные свойства.
Как вы уже знаете, все свойства любого объекта в Delphi располагаются в Object Inspector.

Открываем Delphi, создаем новый проект и выделяем форму. Вкратце пробежимся по основным её свойствам.

Первое свойство, которое мы рассмотрим это свойство Align. Отвечает оно за позиционирование нашей формы на мониторе.
Открываем это свойство и видим несколько значений.

Align

  • alBottom — прилипание формы к низу экрана
  • alClient — растягивание формы на весь экран
  • alCustom — по умолчанию
  • alLeft — прилипание формы к левому краю экрана
  • alNone — без выравнивания
  • alRight — прилипание формы к правому краю экрана
  • alTop — прилипание формы к верху экрана

Следующие свойство AlphaBlend. Это свойство отвечает за прозрачность формы. Выставляем его значение True и ниже видим свойство AlphaBlendValue.
Оно может принимать значения от 1(полная прозрачность) до 255(полная не прозрачность). Выставляем значение 200 и видим прозрачную форму.

AlphaBlend

Выключаем прозрачность формы и двигаемся дальше.

Следующие свойство AutoScroll. Принимает значения Boolean. Я думаю по названию свойства понятно его назначение.
Если какой-либо компонент выходит за границы формы, то на форме автоматически появляется скролл.

Следующие свойство AutoSize, оно находит и подгоняет оптимальный размер формы.
Если мы сейчас выставим значение True и кинем на форму компонент Memo, то это свойство при компиляции уберет все пустые места на форме и как бы обтянет компонент Memo.
Из-за этого мы не сможем изменить размер формы.

AutoSize

Вернем свойству AutoSize значение False и продолжим рассматривать остальные свойства.

Свойство BorderIcons. В нём мы можем задать, какие кнопки мы будем видеть в шапке формы.
Сейчас у нас видны кнопки «свернуть», «развернуть» и «закрыть».
Если мы всем этим кнопкам выставим значение False, то шапка формы будет совершенно пустая.

BorderIcons
BorderIcons

Возвращаем все значения обратно и переходим к следующему свойству.

Свойство BorderStyle, оно отвечает за стиль границ нашей формы. Вы можете сами поэкспериментировать с различными значениями.
Хотелось бы только выделить значение bsNone, то есть после компиляции наша форма совсем не будет иметь границ, это позволяет разрабатывать свои дизайны и скины для формы.

Далее рассматриваем свойство Caption. Оно есть практически у каждого компонента. Сейчас оно имеет значение Form1, давайте изменим его на Программа и мы видим, что заголовок нашей формы поменялся.

Свойство Color отвечает за цвет формы. Очень простое свойство и я думаю вам будет полезнее поэкспериментировать самим.

Свойство Cursor отвечает за то, какой будет курсор при наведении на форму. Выставим значение crHourGlass и скомпилируем программу.
Мы видим, что появляется как бы ложный курсор, обозначающий зависание программы.

Вы наверняка видели в различных программах всплывающие подсказки, которые появляются при задержки курсора на каком-нибудь компоненте.
Свойство Hint как раз отвечает за текст этой подсказки. Напишем Форма и скомпилируем программу. Задерживаем курсор на форме и ничего у нас не всплывает :).
А всё потому, что мы не включили отображение этой подсказки. Включить его можно в свойстве ShowHint, выставив значение True.
Если сейчас скомпилировать и задержать курсор на форме, то мы увидим подсказку.

Далее свойство Icon, оно отвечает за иконку в левом верхнем углу формы. Выделяем свойство Icon, нажимаем на кнопку с тремя точками и у нас открывается окно загрузки иконки.

Icon

Нажимаем на кнопку Load… и выбираем картинку с расширением .ico. Иконки от Delphi лежат в папке C:Program Files (x86)Common FilesBorland SharedImagesIcons.
После того, как выбрали иконку, нажимаем кнопку

и после компиляции видим, что значок программы изменился.
Icon

В свойстве Left задается расстояние в пикселях от левого края экрана до левого края формы.

В свойстве Name пишется имя формы, по которому мы будем обращаться в окне редактора кода.

Свойство Position отвечает за позицию формы после компиляции. Поэкспериментируйте со значениями.

Далее свойство Top, оно аналогично свойству Left, только отсчет пикселей идет от верхнего края экрана и до верхнего края формы.

Свойства Width и Height отвечают за ширину и высоту формы в пикселях.

Свойство Enabled отвечает за активность. Давайте сейчас кинем на форму компонент Button и изменим у него свойство Enabled, выставив значение False.
Компилируем программу и видим, что наша кнопка не активна и на нее нельзя нажать.

Enabled

Ну и последнее свойство, которое мы разберем в этом уроке, свойство Visible. Это свойство отвечает за видимость компонента.
Измените это свойство у кнопки, выставив значение False и скомпилируйте программу, кнопки вы не найдете.

На последок хочу отметить, что большинство свойств у компонентов одинаковое. В этом уроке я рассказал не про все свойства, а только самые основные.
В дальнейших уроках, если мы будем сталкиваться с новым свойством, то я обязательно про него расскажу.

Ну вот и всё! Удачи!
Встретимся в следующем уроке!

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить размер формы access
  • Как изменить размер фонового изображения css
  • Как изменить размер фона рабочего стола на компьютере
  • Как изменить размер фона рабочего стола windows 10
  • Как изменить размер флешки через командную строку

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии