- Как расположить форму и изменить ее размер (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
- Шаг 3. Настройка свойств формы Step 3: Set your form properties
- Настройка свойств формы How to set your form properties
- Дальнейшие действия Next steps
Как расположить форму и изменить ее размер (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.
Шаг 3. Настройка свойств формы Step 3: Set your form properties
Далее окно Свойства используется для изменения внешнего вида формы. Next, you use the Properties window to change the way your form looks.
Настройка свойств формы How to set your form properties
Убедитесь, что отображается конструктор Windows Forms. Be sure you’re looking at Windows Forms Designer. В интегрированной среде разработки Visual Studio откройте вкладку Form1.cs [Design] (или вкладку Form1.vb [Design] в Visual Basic). In the Visual Studio integrated development environment (IDE), choose the Form1.cs [Design] tab (or the Form1.vb [Design] tab in Visual Basic).
Чтобы выделить форму Form1, щелкните в любом ее месте. Choose anywhere inside the form Form1 to select it. Посмотрите на окно Свойства. Теперь оно должно отображать свойства формы. Look at the Properties window, which should now be showing the properties for the form. У формы есть различные свойства. Forms have various properties. Например, можно установить цвет переднего плана и фона, текст заголовка, который отображается в верхней части формы, размер формы и другие свойства. For example, you can set the foreground and background color, title text that appears at the top of the form, size of the form, and other properties.
Если окно Свойства не открывается, остановите приложение, нажав квадратную кнопку Остановить отладку на панели инструментов, или просто закройте окно. If the Properties window doesn’t appear, stop your app by choosing the square Stop Debugging button on the toolbar, or just close the window. Если приложение остановлено, но окно Свойства все равно не отображается, в строке меню выберите Вид > Окно свойств. If the app is stopped and you still don’t see the Properties window, on the menu bar, choose View > Properties Window.
Когда форма будет выбрана, найдите свойство Text в окне Свойства. After the form is selected, find the Text property in the Properties window. В зависимости от того, как отсортирован список, может потребоваться прокрутить вниз. Depending on how the list is sorted, you might need to scroll down. Выберите Text, введите Программа просмотра изображений, а затем нажмите клавишу ВВОД. Choose Text, type Picture Viewer, and then choose Enter. Теперь форма должна содержать текст Программа просмотра изображений в заголовке окна. Окно Свойства должно выглядеть так, как показано на снимке экрана ниже. Your form should now have the text Picture Viewer in its title bar, and the Properties window should look similar to the following screenshot.
**Окно* _ _»Свойства» **Properties* _ _window
Свойства можно упорядочить по категориям или в алфавитном порядке. Properties can be ordered by a Categorized or Alphabetical view. Вы можете переключаться между двумя этими представлениями с помощью кнопок в окне Свойства. You can switch between these two views by using the buttons on the Properties window. В этом руководстве свойства легче находить в представлении, в котором свойства представлены в алфавитном порядке. In this tutorial, it’s easier to find properties through the Alphabetical view.
Вернитесь к конструктору Windows Forms. Go back to Windows Forms Designer. Нажмите нижний правый маркер перетаскивания формы, который представляет собой небольшой белый квадрат в нижнем правом углу формы и показан на рисунке ниже. Choose the form’s lower-right drag handle, which is the small white square in the lower-right of the form and appears as follows.
Маркер перетаскивания Drag handle
Перетащите маркер, чтобы изменить размер формы — она должна стать шире и немного выше. Drag the handle to resize the form so the form is wider and a bit taller.
Посмотрите в окно Свойства и обратите внимание, что изменилось значение свойства Size. Look at the Properties window, and notice that the Size property has changed. Свойство Size меняется при каждом изменении формы. The Size property changes each time you resize the form. Перетащите маркер, чтобы форма имела размер около 550, 350 (не обязательно точно такие значения). Такой размер вполне подходит для этого проекта. Try dragging the form’s handle to resize it to a form size of approximately 550, 350 (no need to be exact), which should work well for this project. В качестве альтернативы можно вводить значения непосредственно в свойстве Size и затем нажимать клавишу ВВОД. As an alternative, you can enter the values directly in the Size property and then choose the Enter key.
Запустите приложение еще раз. Run your app again. Помните, что для запуска приложения можно использовать любой из описанных ниже методов. Remember, you can use any of the following methods to run your app.
Нажмите клавишу F5. Choose the F5 key.
В строке меню выберите Отладка > Начать отладку. On the menu bar, choose Debug > Start Debugging.
На панели инструментов нажмите кнопку Начать отладку, которая показана на рисунке ниже. On the toolbar, choose the Start Debugging button, which appears as follows.
**Кнопка «Начать отладку»* _ _на панели инструментов* **Start Debugging* _ _toolbar button*
Как и ранее, интегрированная среда разработки выполняет сборку приложения и запускает его, после чего открывается окно. Just like before, the IDE builds and runs your app, and a window appears.
Перед переходом к следующему шагу остановите приложение, так как интегрированная среда разработки не позволяет изменять выполняющееся приложение. Before going to the next step, stop your app, because the IDE won’t let you change your app while it’s running. Помните, что для остановки приложения можно использовать любой из описанных ниже методов. Remember, you can use any of the following methods to stop your app.
На панели инструментов нажмите кнопку Остановить отладку. On the toolbar, choose the Stop Debugging button.
В строке меню выберите Отладка > Остановить отладку. On the menu bar, choose Debug > Stop Debugging.
На клавиатуре нажмите клавиши SHIFT+F5. Use your keyboard and press Shift+F5.
Нажмите кнопку X в верхнем углу окна Программа просмотра изображений. Choose the X button in the upper corner of the Picture Viewer window.
Дальнейшие действия Next steps
Предыдущий раздел руководства: Шаг 2. Запуск приложения для просмотра изображений. To return to the previous tutorial step, see Step 2: Run your picture viewer app.