Windows forms form border

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 .

Исключения

Заданное значение находится вне диапазона допустимых значений. 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.

Читайте также:  Включить сетевое обнаружение windows server не сохраняется

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

Определение

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

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

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

Фиксированная граница из одной линии. 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 .

Практическое руководство. Изменение границ в 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.

Читайте также:  Windows console java version

В 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.

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.

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.

Читайте также:  Настройки безопасности для linux

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).

How to change the form border color c#?

I would like to change window form border color (the border with the form title). The example I found in codeplex is too much and confusing. Can any help me on something simpler?

6 Answers 6

Unfortunately, since the form border is drawn by the Operating System, this is a complicated task. There is no real way around that.

Do NOT click the ProjectDistributor link on the CodePlex page below

The CodePlex Project for Drawing Custom Borders makes this very easy, though. Just build the form using SkinnedForm from that project instead of a standard Form, and it should work — you really don’t need to do anything different in your code.

Override it with:

Workaround — Just follow these steps:

  • Set FormBorderStyle to None .
  • Cover the form with a panel and leave some space for border.
  • Set the color you want for the border as the form back color.

Now, the panel serves as the main container and you can change the background as you want and the form serves as the border.

The Final Result

Like previously mentioned, changing the actual color of the border is difficult. The solution above with the panel has limitations like you can’t resize the form. I found a reasonably easy trick without a lot of the other limitations.

  • Create a form
  • Set FormBorderStyle to None
  • Add 4 panels
  • Set the background color of the panels to the color of the border you want
  • Anchor one each to the top, bottom, left, and right
  • Set the height(top/bottom) or width (left/right) to the thickness of the border you want. 2 or 3 looks really good.

It looks like a border, it will resize with the window, and you can drop anything else into the form you want. The limitation is, you must do this as the very first thing you add to the form.

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