- Form. Size Property
- Definition
- Property Value
- Examples
- Remarks
- Form. Client Size Свойство
- Определение
- Значение свойства
- Примеры
- Комментарии
- How to position and size a form (Windows Forms .NET)
- Resize with the designer
- Resize in code
- Resize the current form
- Resize a different form
- Position with the designer
- Position with code
- Move the current form
- Position a different form
- Изменение размеров формы
- Как расположить форму и изменить ее размер (Windows Forms .NET) How to position and size a form (Windows Forms .NET)
- Изменение размера с помощью конструктора Resize with the designer
- Изменение размера в коде Resize in code
- Изменение размера текущей формы Resize the current form
- Изменение размера другой формы Resize a different form
- Расположение с помощью конструктора Position with the designer
- Расположение с помощью кода Position with code
- Перемещение текущей формы Move the current form
- Расположение другой формы Position a different form
Form. Size Property
Definition
Gets or sets the size of the form.
Property Value
A Size that represents the size of the form.
Examples
The following example demonstrates how to create a form that is displayed with an opacity level of 75 percent. The example code creates a new form that is positioned in the center of the screen with an Opacity property set to change the opacity level of the form. The example code also sets the Size property to provide a larger sized form than the default size of the form. This example requires that the method defined in this example is called from another form in an event handler or other method.
Remarks
This property allows you to set both the height and width (in pixels) of the form at the same time instead of setting the Height and Width properties individually. If you want to set the size and location of a form, you can use the DesktopBounds property to size and locate the form based on desktop coordinates or use the Bounds property of the Control class to set the size and location of the form based on screen coordinates.
The maximum value of this property is limited by the resolution of the screen on which the form runs. The value cannot be greater than 12 pixels over each screen dimension (horizontal + 12 and vertical + 12).
On Pocket PC devices, you can create a resizable window by setting FormBorderStyle to None and removing any MainMenu control. On SmartPhone devices, you can never resize a Form — it will always fill the entire screen.
Form. Client Size Свойство
Определение
Возвращает или задает размер клиентской области формы. Gets or sets the size of the client area of the form.
Значение свойства
Объект Size, который представляет размер клиентской области формы. A Size that represents the size of the form’s client area.
Примеры
В следующем примере создается обработчик событий для Resize события формы. The following example creates an event handler for the Resize event of a form. Этот обработчик событий использует свойство ClientSize формы для заполнения всей ее клиентской области кнопкой (Button) с именем button1 . The event handler uses the ClientSize property of the form to make a Button control named button1 fill the entire client area of the form.
Комментарии
Размер клиентской области формы — это размер формы, исключающий границы и заголовок. The size of the client area of the form is the size of the form excluding the borders and the title bar. Клиентская область формы — это область в форме, в которой могут быть помещены элементы управления. The client area of a form is the area within a form where controls can be placed. Это свойство можно использовать для получения правильных размеров при выполнении графических операций или при выборе размера и положения элементов управления на форме. You can use this property to get the proper dimensions when performing graphics operations or when sizing and positioning controls on the form. Чтобы получить размер всей формы, используйте свойство Size или отдельные свойства Height и Width. To get the size of the entire form, use the Size property or use the individual properties Height and Width.
Сейчас невозможно выполнить привязку к этому свойству с помощью параметров приложения. You cannot currently bind to this property using application settings. Дополнительные сведения о параметрах приложения см. в разделе Общие сведения о параметрах приложения. For more information on application settings, see Application Settings Overview.
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.
Изменение размеров формы
Изменение размеров элементов, при изменение размеров формы
Доброго времени суток, подскажите, как в VS2016 реализовать подобное, а именно: Имеются следующая.
Изменение размеров элементов, сохраняя пропорции, при изменении размеров самой формы
Как изменять размеры элементов, сохраняя пропорции, при изменении размеров самой формы?
Изменение размеров элементов управления с изменением размеров формы
подскажите, как сделать так чтобы размер элементов управления изменялся пропорционально размерам.
Динамическое изменение размеров формы
Всем доброго времени суток. Имеется форма, на которой может быть до 10 графиков ZedGraph. Перед.
Sergei
Спасибо, делает то же самое и короче и проще.
Но вопрос, как управлять лишь внутренней частью, а не наружной?
Тематические курсы и обучение профессиям онлайн Профессия С#-разработчик (Skillbox) Архитектор ПО (Skillbox) Профессия Тестировщик (Skillbox) |
Когда задаёте вопрос, обращайте внимание на даты предыдущих сообщений, им уже 5 лет и вряд ли их авторы вам ответят.
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Пропорциональное изменение размеров формы
Как можно заставить форму растягиваться так, чтобы она всегда оставалась квадратной? Пробовал.
Изменение размеров формы без рамок
У меня есть форма на которой есть PictureBox, пытался сделать так if (e.Button ==.
Как запретить изменение размеров формы
Добрый день форумчане, У меня появился вопрос касающийся C#. Вопрос заключается в том, как можно.
Изменение размеров формы при загрузке
вообщем щас надо привести внешнюю состовляющую программы в порядок:) хочу при загрузке формы чтобы.
Как расположить форму и изменить ее размер (Windows Forms .NET) 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. Размер формы по умолчанию обычно имеет ширину и высоту 800 x 500 пикселей. 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.
Изменить размер формы можно во время разработки с помощью Visual Studio, а также во время выполнения с помощью кода. You can change the size of a form at design time with Visual Studio, and at run time with code.
Документация для Руководства по рабочему столу по .NET 5 (и .NET Core) находится в разработке. 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. Выберите форму, а затем найдите панель Свойства в Visual Studio. 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.
Чтобы изменить размер формы, измените свойство Size, которое представляет ширину и высоту формы. 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. Например, если имеется Form1 с кнопкой, то при нажатии на нее вызывается обработчик событий Click для изменения размера формы: 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. Например, предположим, что у вас есть две формы: Form1 (начальная форма в этом примере) и Form2 . For example, let’s say you have two forms, Form1 (the startup form in this example) and Form2 . В Form1 имеется кнопка, которая при нажатии вызывает событие Click . Form1 has a button that when clicked, invokes the Click event. Обработчик этого события создает новый экземпляр формы Form2 , задает размер, а затем отображает его: The handler of this event creates a new instance of the Form2 form, sets the size, and then displays it:
Если свойство Size не задано вручную, размер формы по умолчанию — это размер, заданный во время разработки. 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
При создании и отображении экземпляра формы начальное расположение формы определяется свойством StartPosition. When a form instance is created and displayed, the initial location of the form is determined by the StartPosition property. Свойство Location содержит текущее положение в форме. The Location property holds the current location the form. Оба свойства можно задать с помощью конструктора. Both properties can be set through the designer.
Перечисление FormStartPosition FormStartPosition Enum | Описание Description |
---|---|
CenterParent CenterParent | Форма располагается в центре родительской формы. The form is centered within the bounds of its parent form. |
CenterScreen CenterScreen | Форма располагается по центру текущего экрана. The form is centered on the current display. |
Вручную Manual | Положение формы определяется свойством Расположение. The position of the form is determined by the Location property. |
WindowsDefaultBounds WindowsDefaultBounds | Форма размещается в расположении Windows по умолчанию и ее размер подгоняется под размер по умолчанию, который определен Windows. The form is positioned at the Windows default location and is resized to the default size determined by Windows. |
WindowsDefaultLocation WindowsDefaultLocation | Форма размещается в расположении Windows по умолчанию и не изменяется. The form is positioned at the Windows default location and isn’t resized. |
Значение CenterParent работает только с формами, которые являются либо дочерними формами многодокументного интерфейса (MDI), либо обычными формами, отображаемыми с помощью метода ShowDialog. 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 не влияет на обычную форму, которая отображается с помощью метода Show. CenterParent has no affect on a normal form that is displayed with the Show method. Чтобы разместить форму по центру (переменная form ) другой формы (переменная parentForm ), используйте следующий код: 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. Например, если имеется Form1 с кнопкой, то при нажатии на нее вызывается обработчик событий Click . For example, if you have Form1 with a button on it, that when clicked invokes the Click event handler. Обработчик в этом примере изменяет расположение формы на верхнюю левую часть экрана путем задания свойства Location: 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. Например, предположим, что у вас есть две формы: Form1 (начальная форма в этом примере) и Form2 . For example, let’s say you have two forms, Form1 (the startup form in this example) and Form2 . В Form1 имеется кнопка, которая при нажатии вызывает событие Click . Form1 has a button that when clicked, invokes the Click event. Обработчик этого события создает новый экземпляр формы Form2 и задает ее размер: The handler of this event creates a new instance of the Form2 form and sets the size:
Если свойство Size не задано, размер формы по умолчанию — это размер, заданный во время разработки. If the Size isn’t set, the form’s default size is what it was set to at design-time.