Docking in windows forms

Control. Dock Property

Definition

Gets or sets which control borders are docked to its parent control and determines how a control is resized with its parent.

Property Value

One of the DockStyle values. The default is None.

Exceptions

The value assigned is not one of the DockStyle values.

Examples

The following code example creates a GroupBox and sets some of its common properties. The example creates a TextBox and sets its Location within the group box. Next, it sets the Text property of the group box, and docks the group box to the top of the form. Lastly, it disables the group box by setting the Enabled property to false , which causes all controls contained within the group box to be disabled.

Remarks

Use the Dock property to define how a control is automatically resized as its parent control is resized. For example, setting Dock to DockStyle.Left causes the control to align itself with the left edges of its parent control and to resize as the parent control is resized. Controls are docked in their Z-order, which is the visual layering of controls on a form along the form’s Z-axis (depth).

A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container.

Setting the Margin property on a docked control has no effect on the distance of the control from the edges of its container.

The Anchor and Dock properties are mutually exclusive. Only one can be set at a time, and the last one set takes precedence.

Notes to Inheritors

When overriding the Dock property in a derived class, use the base class’s Dock property to extend the base implementation. Otherwise, you must provide all the implementation. You are not required to override both the get and set methods of the Dock property; you can override only one if needed.

Docking Attribute Класс

Определение

Определяет поведение прикрепления по умолчанию для элемента управления. Specifies the default docking behavior for a control.

Комментарии

Можно создавать новые элементы управления в Windows Forms, производные от существующего элемента управления или из UserControl . You can create new controls in Windows Forms derived either from an existing control or from UserControl. Используйте этот атрибут в новых элементах управления, чтобы описать, как элемент управления должен закрепляться по умолчанию при помещении в форму. Use this attribute on new controls to describe how the control should dock by default when placed on a form.

Конструкторы

Инициализирует новый экземпляр класса DockingAttribute. Initializes a new instance of the DockingAttribute class.

Инициализирует новый экземпляр класса DockingAttribute с заданным поведением прикрепления. Initializes a new instance of the DockingAttribute class with the given docking behavior.

Объект DockingAttribute, используемый по умолчанию для этого элемента управления. The default DockingAttribute for this control.

Читайте также:  Как диски присоединить линукса

Свойства

Получает поведение прикрепления, предоставленное этому атрибуту. Gets the docking behavior supplied to this attribute.

В случае реализации в производном классе возвращает уникальный идентификатор для этого атрибута Attribute. When implemented in a derived class, gets a unique identifier for this Attribute.

(Унаследовано от Attribute)

Методы

Сравнивает произвольный объект с объектом DockingAttribute, чтобы определить, равны ли они. Compares an arbitrary object with the DockingAttribute object for equality.

Хэш-код для этого объекта. The hash code for this object.

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) IsDefaultAttribute()

Задает, является ли этот объект DockingAttribute атрибутом привязывания, используемым по умолчанию. Specifies whether this DockingAttribute is the default docking attribute.

При переопределении в производном классе возвращает значение, указывающее, является ли этот экземпляр равным заданному объекту. When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Унаследовано от Attribute) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) ToString()

Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.

(Унаследовано от Object)

Явные реализации интерфейса

Сопоставляет набор имен соответствующему набору идентификаторов диспетчеризации. Maps a set of names to a corresponding set of dispatch identifiers.

(Унаследовано от Attribute) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Возвращает сведения о типе объекта, которые можно использовать для получения сведений о типе интерфейса. Retrieves the type information for an object, which can be used to get the type information for an interface.

(Унаследовано от Attribute) _Attribute.GetTypeInfoCount(UInt32)

Возвращает количество предоставляемых объектом интерфейсов для доступа к сведениям о типе (0 или 1). Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Унаследовано от Attribute) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Предоставляет доступ к открытым свойствам и методам объекта. Provides access to properties and methods exposed by an object.

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

Можно закреплять элементы управления на краях формы или заполнять их контейнером элемента управления (формой или контейнерным элементом управления). You can dock controls to the edges of your form or have them fill the control’s container (either a form or a container control). Например, проводник закрепляет свой TreeView элемент управления в левой части окна, а его ListView элемент управления — в правой части окна. For example, Windows Explorer docks its TreeView control to the left side of the window and its ListView control to the right side of the window. Используйте Dock свойство для всех видимых Windows Forms элементов управления, чтобы определить режим закрепления. Use the Dock property for all visible Windows Forms controls to define the docking mode.

Элементы управления закрепляются в обратном z-порядке. Controls are docked in reverse z-order.

DockСвойство взаимодействует со AutoSize свойством. The Dock property interacts with the AutoSize property. Дополнительные сведения см. в разделе Общие сведения о свойстве AutoSize. For more information, see AutoSize Property Overview.

Закрепление элемента управления To dock a control

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

Читайте также:  Mail and calendar windows 10 как удалить

В окне Свойства щелкните стрелку справа от Dock Свойства. In the Properties window, click the arrow to the right of the Dock property.

Отобразится редактор, показывающий ряд прямоугольников, представляющих края и центр формы. An editor is displayed that shows a series of boxes representing the edges and the center of the form.

Нажмите кнопку, представляющую границу формы, в которой необходимо закрепить элемент управления. Click the button that represents the edge of the form where you want to dock the control. Чтобы заполнить содержимое формы элемента управления или элемента управления контейнера, щелкните центральную рамку. To fill the contents of the control’s form or container control, click the center box. Щелкните (нет) , чтобы отключить закрепление. Click (none) to disable docking.

Размер элемента управления автоматически изменяется в соответствии с границами закрепленной границы. The control is automatically resized to fit the boundaries of the docked edge.

Наследуемые элементы управления должны быть Protected закрепленными. Inherited controls must be Protected to be able to be docked. Чтобы изменить уровень доступа элемента управления, установите его свойство Modifiers в окне свойства . To change the access level of a control, set its Modifier property in the Properties window.

Control. Dock Свойство

Определение

Возвращает или задает границы элемента управления, прикрепленные к его родительскому элементу управления, и определяет способ изменения размеров элемента управления с его родительским элементом управления. Gets or sets which control borders are docked to its parent control and determines how a control is resized with its parent.

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

Одно из значений перечисления DockStyle. One of the DockStyle values. Значение по умолчанию — None. The default is None.

Исключения

Назначенное значение не является одном из значений DockStyle. The value assigned is not one of the DockStyle values.

Примеры

В следующем примере кода создается GroupBox и задаются некоторые общие свойства. The following code example creates a GroupBox and sets some of its common properties. В примере создается TextBox и задается Location в поле группы. The example creates a TextBox and sets its Location within the group box. Затем задается Text свойство поля группы и закрепляет поле группы в верхней части формы. Next, it sets the Text property of the group box, and docks the group box to the top of the form. Наконец, он отключает поле группы, присвоив Enabled свойству значение false , которое приводит к отключению всех элементов управления, содержащихся в поле группы. Lastly, it disables the group box by setting the Enabled property to false , which causes all controls contained within the group box to be disabled.

Комментарии

Используйте Dock свойство, чтобы определить, как автоматически изменяется размер элемента управления при изменении размера его родительского элемента управления. Use the Dock property to define how a control is automatically resized as its parent control is resized. Например, если задать Dock для параметра значение, DockStyle.Left то элемент управления будет выключаться по левому краю родительского элемента управления и изменять его размер при изменении размера родительского элемента управления. For example, setting Dock to DockStyle.Left causes the control to align itself with the left edges of its parent control and to resize as the parent control is resized. Элементы управления закрепляются в Z-порядке, который является визуальным слоем элементов управления на форме вдоль оси Z формы (глубина). Controls are docked in their Z-order, which is the visual layering of controls on a form along the form’s Z-axis (depth).

Читайте также:  Scsi или sata драйвер для windows

Элемент управления можно закрепить на одной границе родительского контейнера или прикрепить ко всем краям и заполнить родительский контейнер. A control can be docked to one edge of its parent container or can be docked to all edges and fill the parent container.

Установка Margin свойства для закрепленного элемента управления не влияет на расстояние элемента управления от границ контейнера. Setting the Margin property on a docked control has no effect on the distance of the control from the edges of its container.

AnchorСвойства и Dock являются взаимоисключающими. The Anchor and Dock properties are mutually exclusive. В каждый момент времени может быть задан только один, а последний набор имеет приоритет. Only one can be set at a time, and the last one set takes precedence.

Примечания для тех, кто наследует этот метод

При переопределении Dock свойства в производном классе используйте свойство базового класса Dock для расширения базовой реализации. When overriding the Dock property in a derived class, use the base class’s Dock property to extend the base implementation. В противном случае необходимо предоставить всю реализацию. Otherwise, you must provide all the implementation. Переопределение методов и для свойства не требуется get set ; при Dock необходимости можно переопределить только одно из них. You are not required to override both the get and set methods of the Dock property; you can override only one if needed.

How to dock a windows form in C#?

I just would like to know if it is possible to dock a windows form on top of the user screen? I have been trying to do this by manually setting the position of my form to the coordinates I want. But using this method, however, allows the user to change the position of the form just by dragging it. I want to make the form docked to the upper portion of the screen since this window form will server as a menu for the project I am making.

3 Answers 3

I would consider using the Control.Dock property along with one of the DockStyle enumeration values.

You might need to play with the Layout too, so that you may layout your form’s controls differently depending on the DockStyle selected.

You will need, in my point of view, to consider the Control.Location property so that you get to know which DockStyle value to dock your form with.

EDIT #1

Your Windows Form has a Dock property as it inherits from Control .

Let’s consider the following :

Each time your form comes closer to your right-side of the screen, for example, or of the MDI container, you want to dock right, right ? (Little word play here. =P) So, you have to subscribe to the Control.LocationChanged event.

Indeed, instead of constant values, you should use the current desktop resolution and calculate a ratio from it where you want your docking to occur.

***Disclaimer:****This code is provided as-is and has not been tested. This algorithm is hopefully enough to guide you through the docking process as you need it. Further assistance may be brought upon request.* =)

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