Start position windows forms

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.

Читайте также:  Ошибка windows system32 msvcp120 dll

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 Пытаюсь вызвать.

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.

Форма с заданными размерами располагается в центре текущего отображения. 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 the opening form at specific location in C# Windows Forms?

The Location property in the form is set to 0,0 (Properties Window). However, the form doesn’t open at the specified location. Am I missing something?

4 Answers 4

You need to set StartPosition to manual to make the form set start position to the value in Location Property.

Intelisense Summary for FormStartPosition.Manual

The position of the form is determined by the System.Windows.Forms.Control.Location property.

By default the start position is set to be WindowsDefaultLocation which will cause the form to ignore the location you are setting. To easily have the set location enforced, change the StartPosition to Manual.

Setting the Location at 0,0 has no effect if you forget to set StartPosition to FormStartPosition.Manual

This property enables you to set the starting position of the form when it is displayed at run time. The form’s position can be specified manually by setting the Location property or use the default location specified by Windows. 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.

Оцените статью