Windows forms custom border

Практическое руководство. Изменение границ в Windows Forms How to: Change the Borders of Windows Forms

При определении внешнего вида и поведения формы Windows Forms можно выбрать из нескольких стилей границы. You have several border styles to choose from when you are determining the appearance and behavior of your Windows Forms. Изменив FormBorderStyle свойство, можно управлять поведением изменения размеров формы. By changing the FormBorderStyle property, you can control the resizing behavior of the form. Кроме того, параметр FormBorderStyle влияет на способ отображения строки заголовка и кнопок, которые на нем могут отображаться. In addition, setting the FormBorderStyle affects how the caption bar is displayed as well as what buttons might appear on it. Для получения дополнительной информации см. FormBorderStyle. For more information, see FormBorderStyle.

В Visual Studio предусмотрена расширенная поддержка данной задачи. There is extensive support for this task in Visual Studio.

Установка стиля границ формы Windows Forms программными средствами To set the border style of Windows Forms programmatically

Задайте для свойства FormBorderStyle нужный стиль. Set the FormBorderStyle property to the style you want. В следующем примере кода задается стиль границы формы DlgBx1 FixedDialog . The following code example sets the border style of form DlgBx1 to FixedDialog.

Кроме того, если вы выбрали стиль границы для формы, которая предоставляет необязательные кнопки сворачивания и развертывания , можно указать, должна ли работать одна или обе эти кнопки. Additionally, if you have chosen a border style for the form that provides optional Minimize and Maximize buttons, you can specify whether you want either or both of these buttons to be functional. Эти кнопки полезны в тех случаях, когда требуется точно управлять взаимодействием с пользователем. These buttons are useful when you want to closely control the user experience. Кнопки сворачивания и развернуть включены по умолчанию, и их функциональность управляется в окне Свойства . The Minimize and Maximize buttons are enabled by default, and their functionality is manipulated through the Properties window.

Form. Form Border Style Свойство

Определение

Возвращает или задает стиль границы формы. Gets or sets the border style of the form.

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

Объект FormBorderStyle, представляющий стиль отображаемой границы для формы. A FormBorderStyle that represents the style of border to display for the form. Значение по умолчанию — FormBorderStyle.Sizable . The default is FormBorderStyle.Sizable .

Читайте также:  Красивые заметки для windows

Исключения

Заданное значение находится вне диапазона допустимых значений. 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 ,, MinimizeBox MaximizeBox и, StartPosition чтобы изменить внешний вид и функциональность формы на диалоговое окно. The example sets the FormBorderStyle, AcceptButton, CancelButton, MinimizeBox, MaximizeBox, 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.

Комментарии

Стиль границы формы определяет, как выглядит внешний край формы. The border style of the form determines how the outer edge of the form appears. В дополнение к изменению границ для формы, определенные стили границ запрещают размер формы. In addition to changing the border display for a form, certain border styles prevent the form from being sized. Например, FormBorderStyle.FixedDialog стиль границы изменяет границу формы на форму диалогового окна и предотвращает изменение размера формы. For example, the FormBorderStyle.FixedDialog border style changes the border of the form to that of a dialog box and prevents the form from being resized. Стиль границы также может влиять на размер или доступность раздела заголовка в форме. The border style can also affect the size or availability of the caption bar section of a form.

С помощью Sizable стиля невозможно изменить размер окна ниже определенного минимального значения, даже если для параметра задано значение ControlBox false и ему присвоена строка нулевой длины Text . With the Sizable style, it is impossible to resize the window below a certain minimum value, even if you have set ControlBox to false and assigned a zero-length string to Text. Рассмотрите возможность обойти это, используя SizableToolWindow вместо этого стиль. Consider working around this by using the SizableToolWindow style instead.

Form Border Style Перечисление

Определение

Задает стили границ формы. Specifies the border styles for a form.

Фиксированная трехмерная граница. A fixed, three-dimensional border.

Толстая фиксированная граница стиля диалогового окна. A thick, fixed dialog-style border.

Читайте также:  Epson scan utility windows

Фиксированная граница из одной линии. A fixed, single-line border.

Неизменяемая граница окна инструментов. A tool window border that is not resizable. Окно инструментов не отображается ни на панели задач, ни в окне, появляющемся при нажатии пользователем сочетания клавиш ALT+TAB. A tool window does not appear in the taskbar or in the window that appears when the user presses ALT+TAB. Хотя формы, которые задают FixedToolWindow, обычно не отображаются в панели задач, необходимо также гарантировать, что для свойства ShowInTaskbar устанавливается значение false , так как его значение по умолчанию равно true . Although forms that specify FixedToolWindow typically are not shown in the taskbar, you must also ensure that the ShowInTaskbar property is set to false , since its default value is true .

Нет границы. No border.

Граница с изменяемыми размерами. A resizable border.

Изменяемая граница окна инструментов. A resizable tool window border. Окно инструментов не отображается ни на панели задач, ни в окне, появляющемся при нажатии пользователем сочетания клавиш ALT+TAB. A tool window does not appear in the taskbar or in the window that appears when the user presses ALT+TAB.

Примеры

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

Комментарии

Это перечисление используется классом Form. This enumeration is used by the Form class. Он представляет различные стили формы. It represents the different styles of the form. По умолчанию используется стиль Sizable . The default style is Sizable .

How can I add borders to label in Windows Forms?

I’m trying to create a form with white label inside, that when I click on something the form will disappear and only show the label. So far I tried to put the TransparencyKey on Lime and when I click on something I changed the BackColor to Lime and set the FormBorderStyle to None. But the problem is with what I’m doing right now is that the white label has no borders, so You can’t really see it. I know about the BorderStyle property and this is not what I want, I want the border to be exactly around the text so you can see the text above other things. Is there any way to add borders to a label?

Here’s my code, by the way:

5 Answers 5

Well sure; there is a BorderStyle property on Label that can be set to FixedSingle or Fixed3D. FixedSingle is a single-pixel border in the ForeColor color, while Fixed3D is a beveled 3D border using greyscales of the label’s background.

Читайте также:  Windows сообщает что изменилось аппаратное оборудование

EDIT: OK, a little more detail in what exactly is needed. As I see it you have a couple options.

Put two labels, one on top of the other, with the same content and formatting EXCEPT the one in back is white and the one in front is black, and the label in back is offset from the one in front by one pixel in the X and/or Y dimensions. You’ll get a white «shadow» behind the black text. You could even set up four labels, each offset 1 pixel in both X and y, for a complete «halo». You could set this up as a UserControl if you wanted to do this in multiple places; set the text of the control once and the control will populate all 5 labels. You could try playing with font size or weight, but I doubt you’d get something that lined up correctly and had a perfect 1-pixel border around the letters in all cases.

Create an image of your text on a magenta background, ring it in white, and save it as a bitmap with the magenta keyed as the transparent color. Then, use the image in the label (or a PictureBox).

Winforms — How do I create a custom windows border and close/minimise buttons? [closed]

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 1 year ago .

I would like to be able to create a black custom window (with border and controls) like that shipped as part of expression blend, Twirl, or Adobe Lightroom.

How do I create an owner-drawn window?

3 Answers 3

If the custom-chrome tools don’t provide you with the look-and-feel that you want, this kind of thing is easy to do yourself in C#. Basically, you create a borderless form (FormBorderStyle = None) and then create all the controls and borders yourself, by placing controls where you need them (a label for the title bar, command buttons for close and minimize etc.) and/or drawing directly on the form’s surface using the Graphics object.

You also have to implement code to allow the form to be dragged around by its «fake» title bar (see this answer for a sample of how to do this). You may also have to implement your own resizing mechanism (if you need the forms to be resizable).

Finally, although the custom-form code might be a bit clunky, you can implement it on a single form and then have all the other forms in your application inherit from this form, which makes it a very useful technique for custom-skinning an entire application.

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