Windows form resize window

Практическое руководство. Изменение размера формы в Windows Forms How to: Resize Windows Forms

Размер формы Windows Forms можно указать несколькими способами. You can specify the size of your Windows Form in several ways. Вы можете изменить высоту и ширину формы программными средствами, задав новое значение для свойства Size или изменив свойства Height или Width по отдельности. You can change both the height and the width of the form programmatically by setting a new value for the Size property, or adjust the Height or Width properties individually. Если вы используете Visual Studio, можно изменить размер с помощью конструктор Windows Forms. If you’re using Visual Studio, you can change the size using the Windows Forms Designer. См. также руководство. изменение размера Windows Forms с помощью конструктора. Also see How to: Resize Windows Forms Using the Designer.

Программное изменение размера формы Resize a form programmatically

Чтобы определить размер формы во время выполнения, задайте свойство Size формы. Define the size of a form at run time by setting the Size property of the form.

В примере кода ниже размер формы устанавливается равным 100 × 100 пикселей. The following code example shows the form size set to 100 × 100 pixels.

Программное изменение ширины и высоты формы Change form width and height programmatically

Определив свойство Size, измените высоту или ширину формы с помощью свойств Width или Height. After the Size is defined, change either the form height or width by using the Width or Height properties.

В примере кода ниже для ширины формы устанавливается значение 300 пикселей, отсчитываемое от левого края формы. Высота остается неизменной. The following code example shows the width of the form set to 300 pixels from the left edge of the form, whereas the height stays constant.

Измените Width или Height, задав свойство Size. Change Width or Height by setting the Size property.

Однако в примере ниже показано, что этот подход является более громоздким, чем просто задание свойств Width или Height. However, as the following code example shows, this approach is more cumbersome than just setting Width or Height properties.

Изменение размера формы с помощью приращений программными средствами Change form size by increments programmatically

Для увеличения размера формы задайте свойства Width или Height. To increment the size of the form, set the Width and Height properties.

В примере ниже ширина формы увеличивается на 200 пикселей по сравнению с первоначальным значением. The following code example shows the width of the form set to 200 pixels wider than the current setting.

Всегда используйте свойство Height или Width для изменения размеров формы, если вы не устанавливаете значения высоты и ширины одновременно, присваивая свойству Size новую структуру Size. Always use the Height or Width property to change a dimension of a form, unless you are setting both height and width dimensions at the same time by setting the Size property to a new Size structure. Свойство Size возвращает структуру Size, которая является типом значения. The Size property returns a Size structure, which is a value type. Присвоить новое значение свойству типа значения нельзя. You cannot assign a new value to the property of a value type. Поэтому приведенный ниже пример кода компилироваться не будет. Therefore, the following code example will not compile.

Читайте также:  Плейер для windows 10

How to: Resize Windows Forms

You can specify the size of your Windows Form in several ways. You can change both the height and the width of the form programmatically by setting a new value for the Size property, or adjust the Height or Width properties individually. If you’re using Visual Studio, you can change the size using the Windows Forms Designer. Also see How to: Resize Windows Forms Using the Designer.

Resize a form programmatically

Define the size of a form at run time by setting the Size property of the form.

The following code example shows the form size set to 100 Г— 100 pixels.

Change form width and height programmatically

After the Size is defined, change either the form height or width by using the Width or Height properties.

The following code example shows the width of the form set to 300 pixels from the left edge of the form, whereas the height stays constant.

Change Width or Height by setting the Size property.

However, as the following code example shows, this approach is more cumbersome than just setting Width or Height properties.

Change form size by increments programmatically

To increment the size of the form, set the Width and Height properties.

The following code example shows the width of the form set to 200 pixels wider than the current setting.

Always use the Height or Width property to change a dimension of a form, unless you are setting both height and width dimensions at the same time by setting the Size property to a new Size structure. The Size property returns a Size structure, which is a value type. You cannot assign a new value to the property of a value type. Therefore, the following code example will not compile.

Как изменить размер элементов управления на Windows Forms How to: Resize controls on Windows Forms

Можно изменить размер отдельных элементов управления, а также изменить размер различных элементов управления, например Button GroupBox элементов управления и. You can resize individual controls, and you can resize multiple controls of the same or different kind, such as Button and GroupBox controls.

Изменение размера элемента управления To resize a control

В Visual Studio выберите элемент управления, размер которого нужно изменить, и перетащите один из восьми маркеров изменения размера. In Visual Studio, select the control to be resized and drag one of the eight sizing handles.

Выберите элемент управления и нажмите клавиши со стрелками , удерживая нажатой клавишу SHIFT , чтобы изменить размер элемента управления на один пиксель за раз. Select the control and press the arrow keys while holding down the Shift key to resize the control one pixel at a time. Нажмите клавишу стрелка вниз или клавишу со стрелкой вправо , удерживая нажатыми клавиши SHIFT и CTRL , чтобы изменить размер элемента управления с большим шагом. Press the down arrow or right arrow keys while holding down the Shift and Ctrl keys to resize the control in large increments.

Читайте также:  Как установить скаченные курсоры для windows 10

Изменение размера нескольких элементов управления в форме To resize multiple controls on a form

В Visual Studio удерживайте нажатой клавишу CTRL или SHIFT и выберите элементы управления, размер которых необходимо изменить. In Visual Studio, hold down the Ctrl or Shift key and select the controls you want to resize. Размер первого выбранного элемента управления используется для других элементов управления. The size of the first control you select is used for the other controls.

В меню Формат выберите пункт сделать тот же размер и выберите один из четырех параметров. On the Format menu, choose Make Same Size, and select one of the four options. Первые три команды изменяют размеры элементов управления в соответствии с первым выбранным элементом управления. The first three commands change the dimensions of the controls to match the first-selected control.

How to position and size a form (Windows Forms .NET)

When a form is created, the size and location is initially set to a default value. The default size of a form is generally a width and height of 800×500 pixels. The initial location, when the form is displayed, depends on a few different settings.

You can change the size of a form at design time with Visual Studio, and at run time with code.

The Desktop Guide documentation for .NET 5 (and .NET Core) is under construction.

Resize with the designer

After adding a new form to the project, the size of a form is set in two different ways. First, you can set it is with the size grips in the designer. By dragging either the right edge, bottom edge, or the corner, you can resize the form.

The second way you can resize the form while the designer is open, is through the properties pane. Select the form, then find the Properties pane in Visual Studio. Scroll down to size and expand it. You can set the Width and Height manually.

Resize in code

Even though the designer sets the starting size of a form, you can resize it through code. Using code to resize a form is useful when something about your application determines that the default size of the form is insufficient.

To resize a form, change the Size, which represents the width and height of the form.

Resize the current form

You can change the size of the current form as long as the code is running within the context of the form. For example, if you have Form1 with a button on it, that when clicked invokes the Click event handler to resize the form:

Resize a different form

You can change the size of another form after it’s created by using the variable referencing the form. For example, let’s say you have two forms, Form1 (the startup form in this example) and Form2 . Form1 has a button that when clicked, invokes the Click event. The handler of this event creates a new instance of the Form2 form, sets the size, and then displays it:

If the Size isn’t manually set, the form’s default size is what it was set to during design-time.

Position with the designer

When a form instance is created and displayed, the initial location of the form is determined by the StartPosition property. The Location property holds the current location the form. Both properties can be set through the designer.

FormStartPosition Enum Description
CenterParent The form is centered within the bounds of its parent form.
CenterScreen The form is centered on the current display.
Manual The position of the form is determined by the Location property.
WindowsDefaultBounds The form is positioned at the Windows default location and is resized to the default size determined by Windows.
WindowsDefaultLocation The form is positioned at the Windows default location and isn’t resized.

The CenterParent value only works with forms that are either a multiple document interface (MDI) child form, or a normal form that is displayed with the ShowDialog method. CenterParent has no affect on a normal form that is displayed with the Show method. To center a form ( form variable) to another form ( parentForm variable), use the following code:

Position with code

Even though the designer can be used to set the starting location of a form, you can use code either change the starting position mode or set the location manually. Using code to position a form is useful if you need to manually position and size a form in relation to the screen or other forms.

Move the current form

You can move the current form as long as the code is running within the context of the form. For example, if you have Form1 with a button on it, that when clicked invokes the Click event handler. The handler in this example changes the location of the form to the top-left of the screen by setting the Location property:

Position a different form

You can change the location of another form after it’s created by using the variable referencing the form. For example, let’s say you have two forms, Form1 (the startup form in this example) and Form2 . Form1 has a button that when clicked, invokes the Click event. The handler of this event creates a new instance of the Form2 form and sets the size:

If the Size isn’t set, the form’s default size is what it was set to at design-time.

Control. Resize Событие

Определение

Происходит при изменении размеров элемента управления. Occurs when the control is resized.

Тип события

Примеры

В следующем примере кода обрабатывается Resize событие объекта Form . The following code example handles the Resize event of a Form. При изменении размера формы обработчик событий гарантирует, что форма остается квадратной (ее Height и Width остается равной). When the form is resized, the event handler ensures that the form stays square (its Height and Width remain equal). Чтобы выполнить этот пример, убедитесь и свяжите этот метод обработки событий с Resize событием формы. To run this example, make sure and associate this event-handling method with the form’s Resize event.

Комментарии

Чтобы определить Size элемент управления с измененным размером, можно привести sender параметр зарегистрированного ControlEventHandler метода к типу Control и получить его Size свойство (или Height свойства по Width отдельности). To determine the Size of the resized control, you can cast the sender parameter of the registered ControlEventHandler method to a Control and get its Size property (or Height and Width properties individually).

Для управления пользовательскими макетами используйте Layout событие вместо события изменения размера. To handle custom layouts, use the Layout event instead of the Resize event. LayoutСобытие вызывается в ответ на Resize событие, а также в ответ на другие изменения, влияющие на макет элемента управления. The Layout event is raised in response to a Resize event, but also in response to other changes that affect the layout of the control.

Дополнительные сведения об обработке событий см. в разделе обработка и вызов событий. For more information about handling events, see Handling and Raising Events.

Читайте также:  Что такое загрузочный диск линукс
Оцените статью