How to achieve this window style in WinForms?
This is a screen shot from GIMP:
There’s a regular window header on the left and a smaller, more compact window type on the right. It’s something I see from time to time in programs. How can I create such a window in C#?
2 Answers 2
Use the property of your Form object FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
(also SizableToolWindow if you want the user to be able to resize the form).
Look at the properties of Form in properties window, There is property named Style or Sth like that is a dropdown that you can choose between normal windows, dialog and .
UPDATE: FormBorderStyle and it’s values
- None No border.
- FixedSingle A fixed, single-line border.
- Fixed3D A fixed, three-dimensional border.
- FixedDialog A thick, fixed dialog-style border.
- Sizable A resizable border.
- FixedToolWindow A tool window border that is not resizable. A tool window does not appear in the taskbar or in the window that appears when the user presses ALT+TAB. 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.
- SizableToolWindow A resizable tool window border. A tool window does not appear in the taskbar or in the window that appears when the user presses ALT+TAB.
Изменение внешнего вида Windows Forms Changing the Appearance of Windows Forms
Внешний вид приложений Windows Forms можно настраивать различными способами. Например, можно изменять границы, прозрачность, форму, стиль или фоновое изображение. You can customize the look of your Windows Forms applications in many different ways, such as changing the border, opacity, shape, style, or setting a background image for your Windows Forms application.
в этом разделе In This Section
Справочник Reference
Form
Описывает данный класс и предоставляет ссылки на все его члены. Describes this class and has links to all of its members.
FormBorderStyle
Описывается это перечисление и все его члены. Describes this enumeration and contains descriptions of all of its members.
VisualStyleRenderer
Описывает данный класс и предоставляет ссылки на все его члены. Describes this class and has links to all of its members.
Image
Описывает данный класс и предоставляет ссылки на все его члены. Describes this class and has links to all of its members.
Region
Описывает данный класс и предоставляет ссылки на все его члены. Describes this class and has links to all of its members.
Color
Описывает данный класс и предоставляет ссылки на все его члены. Describes this class and has links to all of its members.
Связанные разделы Related Sections
Настройка размера и масштаба формы Windows Forms Adjusting the Size and Scale of Windows Forms
Ссылки на разделы, в которых показано, как изменить размер и масштаб формы. Contains links to topics that show how to change the size and scale of a form.
Объекты Graphics и Drawing в Windows Forms Graphics and Drawing in Windows Forms
Ссылки на разделы, в которых описываются способы рисования в Windows Forms. Contains links to topics that describe how to perform custom drawing on Windows Forms.
Элементы управления Windows Forms со встроенной поддержки рисования владельцем Controls with Built-In Owner-Drawing Support
Описывается поддержка рисования владельцем в элементах управления Windows Forms. List owner-draw support in Windows Forms controls.
Control Styles Перечисление
Определение
Задает стиль и поведение элемента управления. Specifies the style and behavior of a control.
Это перечисление имеет атрибут FlagsAttribute, который разрешает побитовое сочетание значений его элементов.
Если присвоено значение true , элемент управления не обрабатывает сообщение окна WM_ERASEBKGND, чтобы снизить мерцание. If true , the control ignores the window message WM_ERASEBKGND to reduce flicker. Этот стиль следует применять, только если бит UserPaint имеет значение true . This style should only be applied if the UserPaint bit is set to true .
Если присвоено значение true , элемент управления хранит копию текста у себя, а не обращается к Handle каждый раз, когда нужен текст. If true , the control keeps a copy of the text rather than getting it from the Handle each time it is needed. По умолчанию этот стиль имеет значение false . This style defaults to false . Этот режим повышает производительность, но затрудняет синхронизацию текста. This behavior improves performance, but makes it difficult to keep the text synchronized.
Если присвоено значение true , элемент управления является контейнером. If true , the control is a container-like control.
Если присвоено значение true , рисование выполняется в буфере, а после завершения результат выводится на экран. If true , drawing is performed in a buffer, and after it completes, the result is output to the screen. Двойная буферизация предотвращает мерцание, вызываемое обновлением элемента управления. Double-buffering prevents flicker caused by the redrawing of the control. Если для стиля DoubleBuffer задано значение true , следует также установить true для стилей UserPaint и AllPaintingInWmPaint. If you set DoubleBuffer to true , you should also set UserPaint and AllPaintingInWmPaint to true .
Если присвоено значение true , метод OnNotifyMessage(Message) вызывается для каждого сообщения, которое отправляется в метод WndProc(Message) этого элемента управления. If true , the OnNotifyMessage(Message) method is called for every message sent to the control’s WndProc(Message). По умолчанию этот стиль имеет значение false . This style defaults to false . Стиль EnableNotifyMessage не работает в режиме частичного доверия. EnableNotifyMessage does not work in partial trust.
Если присвоено значение true , элемент управления имеет фиксированную высоту при автоматическом масштабировании. If true , the control has a fixed height when auto-scaled. Например, если операция макета пытается изменить размер элемента управления в соответствии с обновлением Font, Height элемента управления не изменяется. For example, if a layout operation attempts to rescale the control to accommodate a new Font, the control’s Height remains unchanged.
Если присвоено значение true , элемент управления имеет фиксированную ширину при автоматическом масштабировании. If true , the control has a fixed width when auto-scaled. Например, если операция макета пытается изменить размер элемента управления в соответствии с обновлением Font, Width элемента управления не изменяется. For example, if a layout operation attempts to rescale the control to accommodate a new Font, the control’s Width remains unchanged.
Если присвоено значение true , элемент управления отображается непрозрачным, а фон не закрашивается. If true , the control is drawn opaque and the background is not painted.
Если присвоено значение true , элемент управления сначала прорисовывается в буфер, а не сразу на экран, что позволяет снизить мерцание. If true , the control is first drawn to a buffer rather than directly to the screen, which can reduce flicker. Если для этого стиля задано значение true , следует также установить true для стиля AllPaintingInWmPaint. If you set this property to true , you should also set the AllPaintingInWmPaint to true .
Если присвоено значение true , элемент управления перерисовывается при изменении его размера. If true , the control is redrawn when it is resized.
Если присвоено значение true , элемент управления может получать фокус. If true , the control can receive focus.
Если присвоено значение true , элемент управления реализует стандартное поведение Click. If true , the control implements the standard Click behavior.
Если присвоено значение true , элемент управления реализует стандартное поведение DoubleClick. If true , the control implements the standard DoubleClick behavior. Этот стиль игнорируется, если бит StandardClick имеет значение, отличное от true . This style is ignored if the StandardClick bit is not set to true .
Если присвоено значение true , элемент управления принимает параметр BackColor c альфа-составляющей, при значении которой менее 255 имитируется прозрачность. If true , the control accepts a BackColor with an alpha component of less than 255 to simulate transparency. Прозрачность имитируется, только если биту UserPaint присвоено значение true , а родительский элемент управления наследуется от класса Control. Transparency will be simulated only if the UserPaint bit is set to true and the parent control is derived from Control.
Если присвоено значение true , элемент управления самостоятельно выполняет обработку событий мыши, и эти события не обрабатываются операционной системой. If true , the control does its own mouse processing, and mouse events are not handled by the operating system.
Если присвоено значение true , отображение элемента управления выполняет сам элемент, а не операционная система. If true , the control paints itself rather than the operating system doing so. Если присвоено значение false , событие Paint не возникает. If false , the Paint event is not raised. Этот стиль применяется только к классам, производным от Control. This style only applies to classes derived from Control.
Указывает, что значение свойства Text (если оно задано для этого элемента управления) определяет стандартное имя и сочетание клавиш для этого элемента управления в Active Accessibility. Specifies that the value of the control’s Text property, if set, determines the control’s default Active Accessibility name and shortcut key.
Примеры
В следующем примере демонстрируется использование ControlStyles с StyleChanged событием. The following example demonstrates a use of ControlStyles with the StyleChanged event.
Комментарии
Элементы управления используют это перечисление в различных свойствах и методах для указания функциональных возможностей. Controls use this enumeration in various properties and methods to specify functionality. Элемент управления может включить стиль, вызвав SetStyle метод и передав соответствующий ControlStyles бит (или биты) и логическое значение, чтобы присвоить битам значения. A control can enable a style by calling the SetStyle method and passing in the appropriate ControlStyles bit (or bits) and the Boolean value to set the bit(s) to. Например, следующая строка кода Visual Basic будет включать двойную буферизацию. For example, the following line of Visual Basic code would enable double-buffering.
Если бит Аллпаинтингинвмпаинт имеет значение true , окно сообщения WM_ERASEBKGND игнорируется, и оба OnPaintBackground OnPaint метода и вызываются непосредственно из WM_PAINT сообщения окна. If the AllPaintingInWmPaint bit is set to true , the window message WM_ERASEBKGND is ignored, and both OnPaintBackground and OnPaint methods are called directly from the window message WM_PAINT. Обычно это снижает мерцание, если только другие элементы управления не отправляют сообщение окна WM_ERASEBKGND элементу управления. This generally reduces flicker unless other controls send the window message WM_ERASEBKGND to the control. Вы можете отправить окно сообщения WM_ERASEBKGRND, чтобы получить псевдо-прозрачный результат, аналогичный Суппортстранспарентбаккколор. Например, ToolBar с плоским видом. You might send the window message WM_ERASEBKGRND to achieve a pseudo-transparent effect similar to SupportsTransparentBackColor; for example, a ToolBar with flat appearance does this.
Чтобы полностью включить двойную буферизацию, можно задать для битов Оптимизеддаублебуффер и Аллпаинтингинвмпаинт значение true . To fully enable double-buffering, you can set the OptimizedDoubleBuffer and AllPaintingInWmPaint bits to true . Однако предпочтительным методом включения двойной буферизации, что дает тот же результат, является установка для DoubleBuffered свойства элемента управления значения true . However the preferred method for enabling double buffering, which yields the same result, is to set the DoubleBuffered property for the control to true .
Если бит Суппортстранспарентбаккколор имеет значение true , а для параметра установлено значение BackColor цвета, альфа-компонент которого меньше 255, OnPaintBackground то имитирует прозрачность, запросив его родительский элемент управления для рисования фона. If the SupportsTransparentBackColor bit is set to true , and the BackColor is set to a color whose alpha component is less than 255, OnPaintBackground will simulate transparency by asking its parent control to paint the background. Это не является истинной прозрачностью. This is not true transparency.
Если между элементом управления и его родителем есть другой элемент управления, текущий элемент управления не будет отображать элемент управления в середине. If there is another control between the control and its parent, the current control will not show the control in the middle.
При щелчке элемента управления, если бит Стандардкликк установлен на true Control.OnClick метод вызывается и вызывает Control.Click событие. When the control is clicked, if the StandardClick bit is set to true the Control.OnClick method is called and it raises the Control.Click event. При двойном щелчке элемента управления, а для битов Стандардкликк и Стандарддаублекликк устанавливается значение true , щелчок передается в DoubleClick событие. When the control is double-clicked, and both the StandardClick and StandardDoubleClick bits are set to true , the click is passed on to the DoubleClick event. Затем Control.OnDoubleClick вызывается метод, который вызывает Control.DoubleClick событие. Then the Control.OnDoubleClick method is called and it raises the Control.DoubleClick event. Однако элемент управления может вызывать OnClick или OnDoubleClick напрямую независимо от значений битов Стандардкликк и стандарддаублекликк. However, the control can call OnClick or OnDoubleClick directly regardless of the StandardClick and StandardDoubleClick bit values. Дополнительные сведения о поведении элементов управления и двойных щелчках см Control.Click Control.DoubleClick . в разделах и. For more information on control click and double click behaviors, see the Control.Click and Control.DoubleClick topics.
Если задан бит Усетекстфоракцессибилити и в свойстве элемента управления указано значение Text , значение свойства этого элемента управления Text определяет имя Active Accessibility по умолчанию для элемента управления и сочетание клавиш. When the UseTextForAccessibility bit is set and there is a value in the control’s Text property, the value of that control’s Text property determines the control’s default Active Accessibility name and shortcut key. В противном случае Label вместо него будет использоваться текст предыдущего элемента управления. Otherwise, the text of the preceding Label control will be used instead. Этот стиль задается по умолчанию. This style is set by default. Некоторые встроенные типы элементов управления, такие как TextBox и ComboBox , сбрасывают этот стиль таким образом, чтобы Text свойства этих элементов управления не использовались Active Accessibility. Certain built-in control types, such as TextBox and ComboBox, reset this style so that the Text property of those controls will not be used by Active Accessibility.