- C# winforms button with solid border, like 3d
- 3 Answers 3
- Not the answer you’re looking for? Browse other questions tagged c# winforms button or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Form. Form Border Style Свойство
- Определение
- Значение свойства
- Исключения
- Примеры
- Комментарии
- Практическое руководство. Изменение границ в Windows Forms How to: Change the Borders of Windows Forms
- Установка стиля границ формы Windows Forms программными средствами To set the border style of Windows Forms programmatically
- Form Border Style Перечисление
- Определение
- Примеры
- Комментарии
- Control Paint. Draw Border Метод
- Определение
- Перегрузки
- DrawBorder(Graphics, Rectangle, Color, ButtonBorderStyle)
- Параметры
- Примеры
- Применяется к
- DrawBorder(Graphics, Rectangle, Color, Int32, ButtonBorderStyle, Color, Int32, ButtonBorderStyle, Color, Int32, ButtonBorderStyle, Color, Int32, ButtonBorderStyle)
- Параметры
C# winforms button with solid border, like 3d
How can I create button with solid border(3d), like picture below on C# winforms?
Panel BorderStyle can be set as Fixed3D , but buttons BorderStyle cannot be set as Fixed3D .
I also already tried FlatAppearance which is actualy flat style.
3 Answers 3
You can customize the Button control this way have thick 3d borders:
- Set the Button FlatStyle to be Flat
- In the FlatApperanace set BorderSize to 0
- In the FlatApperanace set MouseOverBackColor to ControlLight
Then handle Paint event and using ControlPaint.DrawBorder draw a thick 3d border:
And here is the result:
Adding to Reza’s post (thanks Reza!) . you could get a bit fancier and invert the 3D effect when the button is down:
If you don’t care about how thick the border is, you can use the following code. (I choose my checkbox’ appearance as button, and I like it raised when not checked and sunken when checked)
Just in case you don’t know how to use this code: All you need to do is choose your button/checkbox in your designer, then go to the Properties window and choose the Events tab (click the Thunderbolt). Find the event called Paint and type your event handler’s name without the parenthesis in box next to it (such as checkbox_paint). In the code window that pops up afterwards fill in your code. Then you are all set.
Not the answer you’re looking for? Browse other questions tagged c# winforms button or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
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 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 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 .
Control Paint. Draw Border Метод
Определение
Рисует границу для элемента управления в виде кнопки. Draws a border on a button-style control.
Перегрузки
Рисует границу в указанном стиле и цвете, на указанной графической поверхности, а также в пределах указанных границ элемента управления в виде кнопки. Draws a border with the specified style and color, on the specified graphics surface, and within the specified bounds on a button-style control.
Рисует границу для элемента управления в виде кнопки с использованием указанных стилей, цветов и ширины границ, на указанной поверхности, в указанных пределах. Draws a border on a button-style control with the specified styles, colors, and border widths; on the specified graphics surface; and within the specified bounds.
DrawBorder(Graphics, Rectangle, Color, ButtonBorderStyle)
Рисует границу в указанном стиле и цвете, на указанной графической поверхности, а также в пределах указанных границ элемента управления в виде кнопки. Draws a border with the specified style and color, on the specified graphics surface, and within the specified bounds on a button-style control.
Параметры
Вызываемый объект Graphics. The Graphics to draw on.
Rectangle, который представляет размеры границы. The Rectangle that represents the dimensions of the border.
Color границы. The Color of the border.
Одно из значений ButtonBorderStyle, определяющее стиль границы. One of the ButtonBorderStyle values that specifies the style of the border.
Примеры
В следующем примере кода показано использование одного из DrawBorder3D методов. The following code example demonstrates the use of one of the DrawBorder3D methods. Чтобы выполнить этот пример, вставьте следующий код в форму, которая импортирует System.Windows.Forms System.Drawing пространства имен и. To run this example, paste the following code in a form that imports the System.Windows.Forms and System.Drawing namespaces. Убедитесь, что Paint событие формы связано с обработчиком событий в этом примере. Ensure the form’s Paint event is associated with the event handler in this example.
Применяется к
DrawBorder(Graphics, Rectangle, Color, Int32, ButtonBorderStyle, Color, Int32, ButtonBorderStyle, Color, Int32, ButtonBorderStyle, Color, Int32, ButtonBorderStyle)
Рисует границу для элемента управления в виде кнопки с использованием указанных стилей, цветов и ширины границ, на указанной поверхности, в указанных пределах. Draws a border on a button-style control with the specified styles, colors, and border widths; on the specified graphics surface; and within the specified bounds.
Параметры
Вызываемый объект Graphics. The Graphics to draw on.
Rectangle, который представляет размеры границы. The Rectangle that represents the dimensions of the border.
Color левой границы. The Color of the left of the border.
Ширина левой границы. The width of the left border.
Одно из значений ButtonBorderStyle, определяющее стиль левой границы. One of the ButtonBorderStyle values that specifies the style of the left border.
Color верхней границы. The Color of the top of the border.
Ширина верхней границы. The width of the top border.
Одно из значений ButtonBorderStyle, определяющее стиль верхней границы. One of the ButtonBorderStyle values that specifies the style of the top border.
Color правой границы. The Color of the right of the border.
Ширина правой границы. The width of the right border.
Одно из значений ButtonBorderStyle, определяющее стиль правой границы. One of the ButtonBorderStyle values that specifies the style of the right border.
Color нижней границы. The Color of the bottom of the border.
Ширина нижней границы. The width of the bottom border.
Одно из значений ButtonBorderStyle, определяющее стиль нижней границы. One of the ButtonBorderStyle values that specifies the style of the bottom border.