Start position windows form

Form. Start Position Свойство

Определение

Возвращает или задает начальное положение формы в режиме выполнения. Gets or sets the starting position of the form at run time.

Значение свойства

Объект FormStartPosition, представляющий начальное положение формы. A FormStartPosition that represents the starting position of the form.

Исключения

Заданное значение находится вне диапазона допустимых значений. The value specified is outside the range of valid values.

Примеры

В следующем примере создается новый экземпляр класса Form и вызывается ShowDialog метод для вывода формы в виде диалогового окна. The following example creates a new instance of a Form and calls the ShowDialog method to display the form as a dialog box. В примере задаются FormBorderStyle AcceptButton свойства,, CancelButton и, StartPosition чтобы изменить внешний вид и функциональность формы на диалоговое окно. The example sets the FormBorderStyle, AcceptButton, CancelButton, and StartPosition properties to change the appearance and functionality of the form to a dialog box. В примере также используется Add метод Controls коллекции формы для добавления двух Button элементов управления. The example also uses the Add method of the form’s Controls collection to add two Button controls. В примере свойство используется HelpButton для вывода кнопки справки в строке заголовка диалогового окна. The example uses the HelpButton property to display a help button in the caption bar of the dialog box.

Комментарии

Это свойство позволяет задать начальное расположение формы при ее отображении во время выполнения. This property enables you to set the starting position of the form when it is displayed at run time. Положение формы можно указать вручную, задав Location свойство или используя расположение по умолчанию, заданное в Windows. The form’s position can be specified manually by setting the Location property or use the default location specified by Windows. Можно также разместить форму, чтобы она отображалась в центре экрана или в центре ее родительской формы для таких форм, как дочерние формы многодокументного интерфейса (MDI). You can also position the form to display in the center of the screen or in the center of its parent form for forms such as multiple-document interface (MDI) child forms.

Это свойство должно быть задано до отображения формы. This property should be set before the form is shown. Это свойство можно задать до вызова Show ShowDialog метода или в конструкторе формы. You can set this property before you call the Show or ShowDialog method or in your form’s constructor.

Form Start Position Перечисление

Определение

Задает исходное положение формы. Specifies the initial position of a form.

Форма располагается в центре родительской формы. The form is centered within the bounds of its parent form.

Читайте также:  System windows controls datavisualization toolkit

Форма с заданными размерами располагается в центре текущего отображения. The form is centered on the current display, and has the dimensions specified in the form’s size.

Положение формы определяется свойством Location. The position of the form is determined by the Location property.

Положение формы и ее границы определены в Windows по умолчанию. The form is positioned at the Windows default location and has the bounds determined by Windows default.

Форма с заданными размерами размещается в расположении, определенном по умолчанию в Windows. The form is positioned at the Windows default location and has the dimensions specified in the form’s size.

Примеры

В этом примере начальное расположение формы изменяется на центр экрана и отображает сведения о положении с помощью метки. In this example, you change the form’s start position to the center of the screen and display the position information using a label. В этом примере предполагается, что вы уже создали Form именованный объект Form1 . This example assumes that you have already created a Form named Form1 .

Комментарии

Это перечисление используется StartPosition свойством Form класса. This enumeration is used by the StartPosition property of the Form class. Он представляет различные начальные положения формы. It represents the different start positions of the form. Начальной позицией по умолчанию является WindowsDefaultLocation . The default start position is WindowsDefaultLocation .

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:

Читайте также:  Навязчивое обновление windows 10

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.

Start position

Доброго времени суток.
Подскажите пожалуйста, как сделать, чтобы при запуске окно программы находилось в верхнем справа углу?

Добавлено через 2 часа 53 минуты
Разобрался!

Не работает Cursor.Position
Всем привет! Столкнулся с проблемой почему-то не работает Position (никак не вызывается) последняя.

FileStream.Position property
Здравствуйте, уважаемые знатоки 🙂 Обрабатываю текстовый файл, считываю построчно через.

BaseStream.Position — some difficults
Всем привет. Работая со своим сервером столкнулся с проблемой использования BaseStream.Position.

Start Button в VC# Express 2008
Хочу в своей программе реализовать конопку с меню как в Office 2007 например.

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.

Пути ,start up,exe файл
Как из строки string ExePath = System.Windows.Forms.Application.ExecutablePath; выкинуть имя.

Chart установка значения Title.Position
строиться график(1), нужно установить подписи осей как на (2) скрине, много чего перерыл но так и.

Не работает System.Diagnostics.Process.Start
Подскажите почему button2 не работает? Почему System.Diagnostics.Process.Start не читает string.

Process.Start() Не запускает системные утилиты
Имеется путь до msconfig: C:\Windows\System32\msconfig.exe Битность: x64 Пытаюсь вызвать.

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

Чтобы разместить элементы управления, используйте конструктор Windows Forms в Visual Studio или укажите Location свойство. To position controls, use the Windows Forms Designer in Visual Studio or specify the Location property.

Размещение элемента управления в области конструктора конструктор Windows Forms Position a control on the design surface of the Windows Forms Designer

В Visual Studio перетащите элемент управления в соответствующее место с помощью мыши. In Visual Studio, drag the control to the appropriate location with the mouse.

Выберите элемент управления и переместите его с помощью клавиш со СТРЕЛКАми, чтобы более точно расположить его. Select the control and move it with the ARROW keys to position it more precisely. Кроме того, линии привязки помогают точно разместить элементы управления в форме. Also, snaplines assist you in placing controls precisely on your form. Дополнительные сведения см. в разделе Пошаговое руководство. Упорядочивание элементов управления в Windows Forms с помощью линий привязки. For more information, see Walkthrough: Arranging Controls on Windows Forms Using Snaplines.

Размещение элемента управления с помощью окно свойств Position a control using the Properties window

В Visual Studio выберите элемент управления, который требуется разместить. In Visual Studio, select the control you want to position.

В окне Свойства введите значения для Location свойства, разделенные запятыми, чтобы разместить элемент управления в контейнере. In the Properties window, enter values for the Location property, separated by a comma, to position the control within its container.

Первое число (X) — это расстояние от левой границы контейнера; второе число (Y) — это расстояние от верхней границы области контейнера, измеряемое в пикселях. The first number (X) is the distance from the left border of the container; the second number (Y) is the distance from the upper border of the container area, measured in pixels.

Можно развернуть свойство, Location чтобы ввести значения X и Y по отдельности. You can expand the Location property to type the X and Y values individually.

Размещение элемента управления программным способом Position a control programmatically

Присвойте Location свойству элемента управления значение Point . Set the Location property of the control to a Point.

Измените координату X расположения элемента управления с помощью Left подсвойства. Change the X coordinate of the control’s location using the Left subproperty.

Программное увеличение расположения элемента управления Increment a control’s location programmatically

Задайте Left подсвойство, чтобы увеличить координату X элемента управления. Set the Left subproperty to increment the X coordinate of the control.

Используйте Location свойство, чтобы одновременно задать координаты X и Y элемента управления. Use the Location property to set a control’s X and Y positions simultaneously. Чтобы задать расположение по отдельности, используйте Left подсвойство (X) или Top (Y) элемента управления. To set a position individually, use the control’s Left (X) or Top (Y) subproperty. Не пытайтесь неявно задать координаты X и Y Point структуры, представляющей расположение кнопки, так как эта структура содержит копию координат кнопки. Do not try to implicitly set the X and Y coordinates of the Point structure that represents the button’s location, because this structure contains a copy of the button’s coordinates.

Читайте также:  Linux как монтировать раздел linux
Оцените статью