Last Updated :
17 Apr, 2023
A Button is an essential part of an application, or software, or webpage. It allows the user to interact with the application or software. In windows form, you are allowed to set the location of the button in your forms by using Location Property. It is provided by Button class and it helps us to set the coordinates of the upper-left corner of the Button control relative to the upper-left corner of its form. You can use this property in two different methods: 1. Design-Time: It is the easiest method to set the location of the button. Using the following steps:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Location property of the Button programmatically with the help of given syntax:
public System.Drawing.Point Location { get; set; }
Here, the Point is used to represent the upper-left corner of the button relative to the upper-left corner of its container or form. Following steps are used to set the Location property of the Button:
- Step 1: Create a button using the Button() constructor is provided by the Button class.
// Creating Button using Button class Button MyButton = new Button();
- Step 2: After creating Button, set the Location property of the Button provided by the Button class.
// Set the location of the button Mybutton.Location = new Point(225, 198);
- Step 3: And last add this button control to form using Add() method.
// Add this Button to form this.Controls.Add(Mybutton);
- Example:
CSharp
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
namespace
WindowsFormsApp8 {
public
partial
class
Form1 : Form {
public
Form1()
{
InitializeComponent();
}
private
void
Form1_Load(
object
sender, EventArgs e)
{
Label l =
new
Label();
l.AutoSize =
true
;
l.Text = "Do you want to submit
this
form?";
l.Location =
new
Point(222, 145);
this
.Controls.Add(l);
Button Mybutton =
new
Button();
Mybutton.Location =
new
Point(225, 198);
Mybutton.Text = "Submit";
Mybutton.AutoSize =
true
;
Mybutton.BackColor = Color.LightBlue;
this
.Controls.Add(Mybutton);
Button Mybutton1 =
new
Button();
Mybutton1.Location =
new
Point(438, 198);
Mybutton1.Text = "Cancel";
Mybutton1.AutoSize =
true
;
Mybutton1.BackColor = Color.LightPink;
this
.Controls.Add(Mybutton1);
}
}
}
- Output:
Размеры элементов и их позиционирование в контейнере
Последнее обновление: 31.10.2015
Позиционирование
Для каждого элемента управления мы можем определить свойство Location
, которое задает координаты верхнего левого угла элемента относительно контейнера.
При переносе элемента с панели инструментов на форму это свойство устанавливается автоматически. Однако потом в окне Свойств мы можем вручную поправить
координаты положения элемента:
Также мы можем установить позицию элемента в коде:
private void Form1_Load(object sender, EventArgs e) { button1.Location = new Point(50, 50); }
Установка размеров
С помощью свойства Size можно задать размеры элемента:
Дополнительные свойства MaximumSize
и MinimumSize
позволяют ограничить минимальный и максимальный размеры.
Установка свойств в коде:
button1.Size = new Size { Width = 50, Height = 25 }; // установка свойств по отдельности button1.Width = 100; button1.Height = 35;
Свойство Anchor
Дополнительные возможности по позиционировании элемента позволяет определить свойство Anchor. Это свойство определяет расстояние между одной из сторон элемента
и стороной контейнера. И если при работе с контейнером мы будем его растягивать, то вместе с ним будет растягиваться и вложенный элемент.
По умолчанию у каждого добавляемого элемента это свойство равно Top, Left
:
Это значит, что если мы будем растягивать форму влево или вверх, то элемент сохранит расстояние от левой и верхней границы элемента до границ контейнера, в качестве которого
выступает форма.
Мы можем задать четыре возможных значения для этого свойства или их комбинацию:
-
Top
-
Bottom
-
Left
-
Right
Например, если мы изменим значение этого свойства на противоположное — Bottom, Right
, тогда у нас будет неизменным расстояние между правой и нижней стороной элемента и формой.
При этом надо отметить, что данное свойство учитывает расстояние до границ контейнера, а не формы. То есть если у нас на форме есть элемент Panel, а на
Panel расположена кнопка, то на кнопку будет влиять изменение границ Panel, а не формы. Растяжение формы будет в этом случае влиять только, если оно влияет
на контейнер Panel.
Чтобы задать это свойство в коде, надо использовать перечисление AnchorStyles:
button1.Anchor = AnchorStyles.Left; // задаем комбинацию значений button1.Anchor = AnchorStyles.Left | AnchorStyles.Top;
Свойство Dock
Свойство Dock позволяет прикрепить элемент к определенной стороне контейнера. По умолчанию оно имеет значение None, но также позволяет задать еще пять значений:
-
Top
: элемент прижимается к верхней границе контейнера -
Bottom
: элемент прижимается к нижней границе контейнера -
Left
: элемент прижимается к левой стороне контейнера -
Right
: элемент прикрепляется к правой стороне контейнера -
Fill
: элемент заполняет все пространство контейнера
POCO, ACE, Loki и другие продвинутые C++ библиотеки
NullReferenced 13.05.2025
В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .
Паттерны проектирования GoF на C#
UnmanagedCoder 13.05.2025
Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .
Создаем CLI приложение на Python с Prompt Toolkit
py-thonny 13.05.2025
Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .
Конвейеры ETL с Apache Airflow и Python
AI_Generated 13.05.2025
ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .
Выполнение асинхронных задач в Python с asyncio
py-thonny 12.05.2025
Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .
Работа с gRPC сервисами на C#
UnmanagedCoder 12.05.2025
gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .
CQRS (Command Query Responsibility Segregation) на Java
Javaican 12.05.2025
CQRS — Command Query Responsibility Segregation, или разделение ответственности команд и запросов. Суть этого архитектурного паттерна проста: операции чтения данных (запросы) отделяются от операций. . .
Шаблоны и приёмы реализации DDD на C#
stackOverflow 12.05.2025
Когда я впервые погрузился в мир Domain-Driven Design, мне показалось, что это очередная модная методология, которая скоро канет в лету. Однако годы практики убедили меня в обратном. DDD — не просто. . .
Исследование рантаймов контейнеров Docker, containerd и rkt
Mr. Docker 11.05.2025
Когда мы говорим о контейнерных рантаймах, мы обсуждаем программные компоненты, отвечающие за исполнение контейнеризованных приложений. Это тот слой, который берет образ контейнера и превращает его в. . .
Micronaut и GraalVM — будущее микросервисов на Java?
Javaican 11.05.2025
Облачные вычисления безжалостно обнажили ахиллесову пяту Java — прожорливость к ресурсам и медлительный старт приложений. Традиционные фреймворки, годами радовавшие корпоративных разработчиков своей. . .
During its lifetime, the form is likely to take up space at some location. The initial location for the form is governed by the StartPosition property, which can have one of several values from the FormStartPosition enumeration:
enum FormStartPosition { CenterParent, CenterScreen, Manual, WindowsDefaultBounds, WindowsDefaultLocation, // default }
These values have the following behavior:
-
WindowsDefaultLocation . The form’s starting position will be determined by Windows , which will pick a location staggered from the upper-left corner of the screen toward the lower right in an attempt to make sure that new windows neither cover each other nor fall off the screen. The form will be shown with whatever the Size property was set to in the Designer.
-
WindowsDefaultBounds . Windows will be asked to determine a default size as well as location.
-
CenterScreen . The form will be centered on the desktop , that area not taken up by the shell taskbar and the like.
-
CenterParent . The form will be centered over the owner (or the currently active form, if there’s no owner) when ShowDialog is used. If Show is used, the behavior is that of WindowsDefaultLocation.
-
Manual . Allows you to set the initial location and the size of the form without any Windows intervention.
The size and location of the form are exposed via the Size and Location properties, of type Size and Point, respectively (both from the System.Drawing namespace). As a shortcut, the properties of the size of a form are exposed directly via the Height and Width form properties, and those of the location are exposed via the Left, Right, Top, and Bottom properties. Figure 2.3 shows the basic size and location properties on a form.
Figure 2.3. The DesktopLocation, Location, ClientSize, and Size Properties
When the upper-left corner of a form changes, that’s a move , which can be handled in the Move or LocationChanged event handler. When the width or height of a form changes, that’s a resize , which can be handled in the Resize or SizeChanged event handler. [6] Sometimes one gesture of the mouse can cause all move and size events to happen. For example, resizing a form by dragging the top-left corner would change the location and the size of the form.
[6] Why are there two events for move and two more for resize? The XxxChanged events are so named to be consistent with data binding. The Move and Resize events are more familiar to Visual Basic programmers and are kept for their benefit. Both events are functionally equivalent.
The location of the form is in absolute screen coordinates. If you’re interested in the location of the form relative to the desktop ”so that, for example, your form’s caption never appears underneath the shell’s taskbar ”then even if it’s on the top edge, as shown in Figure 2.3, you can use the DesktopLocation property. Here’s an example:
void Form3_Load(object sender, EventArgs e) { // Could end up under the shell's taskbar this.Location = new Point(1, 1); // Will always be in the desktop this.DesktopLocation = new Point(1, 1); // A simpler form of the preceding line this.SetDesktopLocation(1, 1); }
Locations are expressed via the Point structure from the System.Drawing namespace, the interesting parts of which are shown here:
struct Point { // Fields public static readonly Point Empty; // Constructors public Point(int x, int y); // Properties public bool IsEmpty { get; } public int X { get; set; } public int Y { get; set; } // Methods public static Point Ceiling(PointF value); public void Offset(int dx, int dy); public static Point Round(PointF value); public virtual string ToString(); public static Point Truncate(PointF value); }
The PointF structure is very similar to the Point structure, but PointF is used in drawing applications when more precise floating point measurements are required. Sometimes you’ll need to convert from a Point to a PointF object to be able to call some methods or set some properties. You can do so without any extra effort:
// Can convert directly from Point to PointF Point pt1 = new Point(10, 20); PointF pt2 = pt1; // Yields PointF(10.0f, 20.0f)
However, because floating point numbers contain extra precision that will be lost in the conversion, you’ll need to be explicit about how to convert from a PointF to a Point object using the static Truncate, Round, and Ceiling methods of the Point class:
// Need to be explicit when converting from a PointF to a Point PointF pt1 = new PointF(1.2f, 1.8f); Point pt2 = Point.Truncate(pt1); // Yields Point(1, 1); Point pt3 = Point.Round(pt1); // Yields Point(1, 2); Point pt4 = Point.Ceiling(pt1); // Yields Point(2, 2);
The size of a window is reflected in the Size property, also from System.Drawing (Size also has a SizeF counterpart and provides the same capabilities for conversion):
struct Size { // Fields public static readonly Size Empty; // Constructors public Size(int width, int height); // Properties public int Height { get; set; } public bool IsEmpty { get; } public int Width { get; set; } // Methods public static Size Ceiling(SizeF value); public virtual bool Equals(object obj); public static Size Round(SizeF value); public virtual string ToString(); public static Size Truncate(SizeF value); }
Although the Size property represents the size of the entire window, a form isn’t responsible for rendering all of its contents. The form can have edges, a caption, and scrollbars, all of which are drawn by Windows. The part that the form is responsible for is the ClientSize, as shown in Figure 2.3. It’s useful to save the ClientSize property between application sessions because it’s independent of the current adornment settings the user has established. Similarly, resizing the form to make sure there’s enough space to render your form’s state is often related to the client area of the form and not to the size of the form as a whole:
void Form2_Load(object sender, EventArgs e) { this.ClientSize = new Size(100, 100); // Calls SetClientSizeCore this.SetClientSizeCore(100, 100); }
A Rectangle combines a Point and a Size and also has a RectangleF counterpart. Structure RectangleThe Bounds property gives a rectangle of the form relative to the screen, whereas the DesktopBounds property is a rectangle relative to the desktop for top-level windows (and not for child windows). The ClientRectangle property is a rectangle relative to the form itself, describing the client area of the form. Of the three, ClientRectangle tends to be the most used, if for no other reason than to describe which area to use when drawing:
void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.FillEllipse(Brushes.Yellow, this.ClientRectangle); g.DrawEllipse(Pens.DarkBlue, this.ClientRectangle); }
Also, it’s sometimes necessary to convert a point that’s relative to the screen to one that’s relative to the client or vice versa. For example, the HelpRequest event, generated when the user clicks on the Help button and then clicks on a control, is sent to the handler in screen coordinates. However, to determine which control was clicked on requires the mouse position in client coordinates. You can convert between the two coordinate systems by using PointToScreen and PointToClient:
void Form1_HelpRequested(object sender, HelpEventArgs e) { // Convert screen coordinates to client coordinates Point pt = this.PointToClient(e.MousePos); // Look for control user clicked on foreach( Control control in this.Controls ) { if( control.Bounds.Contains(pt) ) { Control controlNeedingHelp = control; ... break; } } }
To translate an entire rectangle between screen and client coordinates, you can also use RectangleToScreen and RectangleToClient.
Restricting Form Size
Often our careful control layouts or rendering requirements dictate a certain minimum amount of space. Less often, our forms can’t be made to take advantage of more than a certain amount of space (although anchoring and docking, described later, should help with that). Either way, it’s possible to set a form’s minimum or maximum size via the MinimumSize and MaximumSize properties, respectively. The following example sets a fixed height of 200, a minimum width of 300, and a maximum width so large as to be unlimited:
void Form2_Load(object sender, EventArgs e) { // min width is 300, min height is 200 this.MinimumSize = new Size(300, 200); // max width is unlimited, max height is 200 this.MaximumSize = new Size(int.MaxValue, 200); }
Notice that the code uses the maximum value of an integer to specify that there is no effective maximum width on the form. You may be tempted to use zero for this value instead, but if either the Width or the Height property of the Size used to set the minimum or maximum is nonzero, then both values are used. This would set the maximum size of your form to zero instead of «no maximum.»
One other setting that governs a form’s size and location is WindowState, which can be one of the values from the FormWindowState enumeration:
enum FormWindowState { Maximized, Minimized, Normal, // Form.WindowState default value }
By default, the WindowState is set to Normal, which means that it’s not maximized to take up the entire desktop, nor is it minimized so that none of the form shows at all and only a button is shown in the taskbar. Your program can get or set this property at will to manage the state of your form. However, if you’re saving the size and location of your form between application sessions, you may decide to reset the WindowState to Normal so that the size being saved represents the size in the normal state and not the minimized or maximized size:
void Form2_Closing(object sender, CancelEventArgs e) { // Capture the properties before the form is gone FormWindowState state = this.WindowState; this.WindowState = FormWindowState.Normal; Point location = this.Location; Size size = this.ClientSize; // ... save state, location and size properties between sessions ... // ... restore properties in Load event ... }
For a description of how and where to keep application settings between sessions, read Chapter 11: Applications and Settings.
Z-Order
Another location property that you may let your users influence or keep between sessions is the TopLevel property. So far I’ve discussed location in terms of x and y. However, as the user switches between windows, Windows also juggles the z-order , which dictates which windows are drawn on top of one another.
Furthermore, z-order is split into two tiers. Normal windows are drawn lowest z-order to highest, front to back. Above all the normal windows are the topmost windows, which are also drawn relative to each other, lowest z-order to highest, but no matter the z-order, are always drawn on top of any normal window. For an example of a topmost window, pressing Ctrl+Shift+ESC under many versions of Windows will bring up Task Manager. By default, it’s a topmost window and always draws on top of normal windows, whether or not it is the active window. You can change this behavior (I always do) by unchecking the Options Always On Top setting. If Task Manager were implemented using WinForms, it would implement this feature by toggling the TopMost property on its main form.
Example. Here we adjust the position of the window before it is shown. Look at the Screen.PrimaryScreen WorkingArea.Height and Width properties above. These are the most important trick to this project.
Here: We see the approach we will use to position windows like a palette relative to another window. This will position to the bottom.
Info: The example shows how to get the sizes of both windows. We must know the positions and sizes of both windows we want to position.
So: We must get the size of the working area, meaning the size of the user’s desktop minus the taskbar. We use the WorkingArea class for this.
Finally: Before we place the form, we need to make sense that our new position makes sense. Then we place the new Form.
C# program that positions a sub-window
/// <summary>
/// A Windows Form.
/// </summary>
public partial class MainWindow : Form
{
/// <summary>
/// The Windows Form we want to position.
/// </summary>
ReporterWindow _reporterWin = new ReporterWindow();
public MainWindow ()
{
InitializeComponent();
}
private void reportMoveToolStripMenuItem_Click(object sender, EventArgs e)
{
// This is an event handler triggered by a menu item (or button).
PositionReporterEdge(); // Position the window.
_reporterWin.Show();
}
/// <summary>
/// Position the «Reporter» form next to the current form.
/// </summary>
private void PositionReporterEdge()
{
int screenHeight = Screen.PrimaryScreen.
WorkingArea
.Height;
int screenWidth = Screen.PrimaryScreen.
WorkingArea
.Width;
Point parentPoint = this.
Location
;
int parentHeight = this.Height;
int parentWidth = this.Width;
int childHeight = _reporterWin.Height;
int childWidth = _reporterWin.Width;
int resultX;
int resultY;
if ((parentPoint.Y + parentHeight + childHeight) > screenHeight)
{
// If we would move off the screen, position near the top.
resultY = parentPoint.Y + 50; // move down 50
resultX = parentPoint.X;
}
else
{
// Position on the edge.
resultY = parentPoint.Y + parentHeight;
resultX = parentPoint.X;
}
// set our child form to the new position
_reporterWin.Location = new Point(resultX, resultY);
}
}