Windows form control box

Form. Control Box Property

Definition

Gets or sets a value indicating whether a control box is displayed in the caption bar of the form.

Property Value

true if the form displays a control box in the upper-right corner of the form; otherwise, false . The default is true .

Examples

The following example uses the ControlBox, FormBorderStyle, MaximizeBox, MinimizeBox, and StartPosition properties to create a form that does not have any border or caption box. The form created in this example could be used to create a splash screen for an application. The example requires that the example’s method is defined in a form class and called when the form is being initialized.

Remarks

If the ControlBox property is set to true , the control box is displayed in the upper-right corner of the caption bar. The control box can include minimize, maximize, and help buttons in addition to a close button. For the ControlBox property to have any effect, you must also set the form’s FormBorderStyle property to FormBorderStyle.FixedSingle, FormBorderStyle.Sizable, FormBorderStyle.Fixed3D, or FormBorderStyle.FixedDialog.

If you set ControlBox to false and also set the Location property, the Size property of the form is not updated to reflect that the non-client area of the form has been hidden. To fix this problem, put the code that alters the Location property in the HandleCreated event handler.

When set to false , the ControlBox property has no effect on a Multiple-document interface (MDI) child form that is displayed maximized at time of creation.

Элемент управления TextBox (Windows Forms) TextBox Control (Windows Forms)

Windows Forms текстовые поля используются для получения входных данных от пользователя или для вывода текста. Windows Forms text boxes are used to get input from the user or to display text. TextBox Элемент управления обычно используется для редактируемого текста, хотя его также можно сделать доступным только для чтения. The TextBox control is generally used for editable text, although it can also be made read-only. Текстовые поля могут отображать несколько строк, переносить текст в размер элемента управления и добавлять базовое форматирование. Text boxes can display multiple lines, wrap text to the size of the control, and add basic formatting. TextBox Элемент управления допускает один формат текста, отображаемого или вводимых в элементе управления. The TextBox control allows a single format for text displayed or entered in the control.

в этом разделе In This Section

Общие сведения об элементе управления TextBox TextBox Control Overview
Описание элемента управления, его основных возможностей и свойств. Explains what this control is and its key features and properties.

Практическое руководство. Управление положением курсора в элементе управления TextBox в Windows Forms How to: Control the Insertion Point in a Windows Forms TextBox Control
Инструкции по указанию места, где точка вставки появляется при первом получении фокуса элементом управления «поле ввода». Gives directions for specifying where the insertion point appears when an edit control first gets the focus.

Практическое руководство. Создание текстового поля только для чтения How to: Create a Read-Only Text Box
Описывает, как предотвратить изменение содержимого текстового поля. Describes how to prevent the contents of a text box from being changed.

Практическое руководство. Добавление кавычек в строку How to: Put Quotation Marks in a String
Описание добавления кавычек к строке в текстовом поле. Explains adding quotation marks to a string in a text box.

Справочник Reference

Класс TextBox TextBox class
Описание класса и всех его членов. Describes this class and has links to all its members.

Элементы управления для использования в формах Windows Forms Controls to Use on Windows Forms
Полный список элементов управления Windows Forms со ссылками на информацию об их применении. Provides a complete list of Windows Forms controls, with links to information on their use.

Create a Windows Forms Toolbox Control

The Windows Forms Toolbox Control item template that is included in the Visual Studio Extensibility Tools (VS SDK), lets you create a Toolbox control that is automatically added when the extension is installed. This walkthrough shows how to use the template to create a simple counter control that you can distribute to other users.

Prerequisites

Starting in Visual Studio 2015, you do not install the Visual Studio SDK from the download center. It is included as an optional feature in Visual Studio setup. You can also install the VS SDK later on. For more information, see Install the Visual Studio SDK.

Create the Toolbox Control

The Windows Forms Toolbox Control template creates an undefined user control and provides all of the functionality that is required to add the control to the Toolbox.

Create an extension with a Windows Forms Toolbox Control

Create a VSIX project named MyWinFormsControl . You can find the VSIX project template in the New Project dialog, by searching for «vsix».

Читайте также:  Телеграмм для линукс дебиан

When the project opens, add a Windows Forms Toolbox Control item template named Counter . In the Solution Explorer, right-click the project node and select Add > New Item. In the Add New Item dialog, go to Visual C# > Extensibility and select Windows Forms Toolbox Control

This adds a user control, a ProvideToolboxControlAttribute RegistrationAttribute to place the control in the Toolbox, and a Microsoft.VisualStudio.ToolboxControl Asset entry in the VSIX manifest for deployment.

Build a user interface for the control

The Counter control requires two child controls: a Label to display the current count, and a Button to reset the count to 0. No other child controls are required because callers will increment the counter programmatically.

To build the user interface

In Solution Explorer, double-click Counter.cs to open it in the designer.

Remove the Click Here ! button that is included by default when you add the Windows Forms Toolbox Control item template.

From the Toolbox, drag a Label control and then a Button control below it to the design surface.

Resize the overall user control to 150, 50 pixels, and resize the button control to 50, 20 pixels.

In the Properties window, set the following values for the controls on the design surface.

Control Property Value
Label1 Text «»
Button1 Name btnReset
Button1 Text Reset

Code the user control

The Counter control will expose a method to increment the counter, an event to be raised whenever the counter is incremented, a Reset button, and three properties to store the current count, the display text, and whether to show or hide the Reset button. The ProvideToolboxControl attribute determines where in the Toolbox the Counter control will appear.

To code the user control

Double-click the form to open its load event handler in the code window.

Above the event handler method, in the control class create an integer to store the counter value and a string to store the display text as shown in the following example.

Create the following public property declarations.

Callers can access these properties to get and set the display text of the counter and to show or hide the Reset button. Callers can obtain the current value of the read-only Value property, but they cannot set the value directly.

Put the following code in the Load event for the control.

Setting the Label text in the Load event enables the target properties to load before their values are applied. Setting the Label text in the constructor would result in an empty Label.

Create the following public method to increment the counter.

Add a declaration for the Incremented event to the control class.

Callers can add handlers to this event to respond to changes in the value of the counter.

Return to design view and double-click the Reset button to generate the btnReset_Click event handler. Then, fill it in as shown in the following example.

Immediately above the class definition, in the ProvideToolboxControl attribute declaration, change the value of the first parameter from «MyWinFormsControl.Counter» to «General» . This sets the name of the item group that will host the control in the Toolbox.

The following example shows the ProvideToolboxControl attribute and the adjusted class definition.

Test the control

To test a Toolbox control, first test it in the development environment and then test it in a compiled application.

To test the control

Press F5 to Start Debugging.

This command builds the project and opens a second Experimental instance of Visual Studio that has the control installed.

In the Experimental instance of Visual Studio, create a Windows Forms Application project.

In Solution Explorer, double-click Form1.cs to open it in the designer if it is not already open.

In the Toolbox, the Counter control should be displayed in the General section.

Drag a Counter control to your form, and then select it. The Value , Message , and ShowReset properties will be displayed in the Properties window, together with the properties that are inherited from UserControl.

Set the Message property to Count: .

Drag a Button control to the form, and then set the name and text properties of the button to Test .

Double-click the button to open Form1.cs in code view and create a click handler.

In the click handler, call counter1.Increment() .

In the constructor function, after the call to InitializeComponent , type counter1«.«Incremented += and then press Tab twice.

Visual Studio generates a form-level handler for the counter1.Incremented event.

Highlight the Throw statement in the event handler, type mbox , and then press Tab twice to generate a message box from the mbox code snippet.

On the next line, add the following if / else block to set the visibility of the Reset button.

Press F5.

The form opens. The Counter control displays the following text.

Count: 0

Select Test.

The counter increments and Visual Studio displays a message box.

Close the message box.

The Reset button disappears.

Select Test until the counter reaches 5 closing the message boxes each time.

The Reset button reappears.

Form. Control Box Свойство

Определение

Возвращает или задает значение, указывающее, отображается ли кнопка оконного меню в строке заголовка формы. Gets or sets a value indicating whether a control box is displayed in the caption bar of the form.

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

true Если в форме в правом верхнем углу формы отображается поле элемента управления; в противном случае — false . true if the form displays a control box in the upper-right corner of the form; otherwise, false . Значение по умолчанию — true . The default is true .

Примеры

В следующем примере используются ControlBox свойства, FormBorderStyle , MaximizeBox , MinimizeBox и StartPosition для создания формы, не имеющей границы или поля заголовка. The following example uses the ControlBox, FormBorderStyle, MaximizeBox, MinimizeBox, and StartPosition properties to create a form that does not have any border or caption box. Форма, созданная в этом примере, может использоваться для создания экрана-заставки для приложения. The form created in this example could be used to create a splash screen for an application. В примере требуется, чтобы метод примера был определен в классе формы и вызывался при инициализации формы. The example requires that the example’s method is defined in a form class and called when the form is being initialized.

Комментарии

Если ControlBox свойство имеет значение true , поле элемента управления отображается в правом верхнем углу строки заголовка. If the ControlBox property is set to true , the control box is displayed in the upper-right corner of the caption bar. Окно элемента управления может содержать кнопки сворачивания, развернуть и Справка в дополнение к кнопке Закрыть. The control box can include minimize, maximize, and help buttons in addition to a close button. ControlBox Чтобы свойство имело никакого влияния, необходимо также присвоить FormBorderStyle свойству формы значение FormBorderStyle.FixedSingle , FormBorderStyle.Sizable , FormBorderStyle.Fixed3D или FormBorderStyle.FixedDialog . For the ControlBox property to have any effect, you must also set the form’s FormBorderStyle property to FormBorderStyle.FixedSingle, FormBorderStyle.Sizable, FormBorderStyle.Fixed3D, or FormBorderStyle.FixedDialog.

Если задано ControlBox значение false , а также задано Location свойство, Size свойство формы не обновляется с учетом скрытия неклиентской области формы. If you set ControlBox to false and also set the Location property, the Size property of the form is not updated to reflect that the non-client area of the form has been hidden. Чтобы устранить эту проблему, добавьте код, который изменяет Location свойство в HandleCreated обработчике событий. To fix this problem, put the code that alters the Location property in the HandleCreated event handler.

Если задано значение false , ControlBox свойство не оказывает влияния на дочернюю форму многодокументного интерфейса (MDI), которая отображается в режиме, развернутой во время создания. When set to false , the ControlBox property has no effect on a Multiple-document interface (MDI) child form that is displayed maximized at time of creation.

Controls to Use on Windows Forms

The following is an alphabetic list of controls and components that can be used on Windows Forms. In addition to the Windows Forms controls covered in this section, you can add ActiveX and custom controls to Windows Forms. If you do not find the control you need listed here, you can also create your own. For details, see Developing Windows Forms Controls at Design Time. For more information about choosing the control you need, see Windows Forms Controls by Function.

Visual Basic controls are based on classes provided by the .NET Framework.

In This Section

Windows Forms Controls by Function
Lists and describes Windows Forms controls based on the .NET Framework.

Controls with Built-In Owner-Drawing Support
Describes how to alter aspects of a control’s appearance that are not available through properties.

BackgroundWorker Component
Enables a form or control to run an operation asynchronously.

BindingNavigator Control
Provides the navigation and manipulation user interface (UI) for controls that are bound to data.

BindingSource Component
Encapsulates a data source for binding to controls.

Button Control
Presents a standard button that the user can click to perform actions.

CheckBox Control
Indicates whether a condition is on or off.

CheckedListBox Control
Displays a list of items with a check box next to each item.

ColorDialog Component
Allows the user to select a color from a palette in a pre-configured dialog box and to add custom colors to that palette.

ComboBox Control
Displays data in a drop-down combo box.

ContextMenu Component
Provides users with an easily accessible menu of frequently used commands that are associated with the selected object. Although ContextMenuStrip replaces and adds functionality to the ContextMenu control of previous versions, ContextMenu is retained for both backward compatibility and future use if so desired.

ContextMenuStrip Control
Represents a shortcut menu. Although ContextMenuStrip replaces and adds functionality to the ContextMenu control of previous versions, ContextMenu is retained for both backward compatibility and future use if so desired.

DataGrid Control
Displays tabular data from a dataset and allows for updates to the data source.

DataGridView Control
Provides a flexible, extensible system for displaying and editing tabular data.

DateTimePicker Control
Allows the user to select a single item from a list of dates or times.

Dialog-Box Controls and Components
Describes a set of controls that allow users to perform standard interactions with the application or system.

DomainUpDown Control
Displays text strings that a user can browse through and select from.

ErrorProvider Component
Displays error information to the user in a non-intrusive way.

FileDialog Class Provides base-class functionality for file dialog boxes.

FlowLayoutPanel Control
Represents a panel that dynamically lays out its contents horizontally or vertically.

FolderBrowserDialog Component
Displays an interface with which users can browse and select a directory or create a new one.

FontDialog Component
Exposes the fonts that are currently installed on the system.

GroupBox Control
Provides an identifiable grouping for other controls.

HelpProvider Component
Associates an HTML Help file with a Windows-based application.

HScrollBar and VScrollBar Controls
Provide navigation through a list of items or a large amount of information by scrolling either horizontally or vertically within an application or control.

ImageList Component
Displays images on other controls.

Label Control
Displays text that cannot be edited by the user.

LinkLabel Control
Allows you to add Web-style links to Windows Forms applications.

ListBox Control
Allows the user to select one or more items from a predefined list.

ListView Control
Displays a list of items with icons, in the manner of Windows Explorer.

MainMenu Component
Displays a menu at run time. Although MenuStrip replaces and adds functionality to the MainMenu control of previous versions, MainMenu is retained for both backward compatibility and future use if you choose.

MaskedTextBox Control
Constrains the format of user input in a form.

MenuStrip Control
Provides a menu system for a form. Although MenuStrip replaces and adds functionality to the MainMenu control of previous versions, MainMenu is retained for both backward compatibility and future use if you choose.

MonthCalendar Control
Presents an intuitive graphical interface for users to view and set date information.

NotifyIcon Component
Displays icons for processes that run in the background and would not otherwise have user interfaces.

NumericUpDown Control
Displays numerals that a user can browse through and select from.

OpenFileDialog Component
Allows users to open files by using a pre-configured dialog box.

PageSetupDialog Component
Sets page details for printing through a pre-configured dialog box.

Panel Control
Provide an identifiable grouping for other controls, and allows for scrolling.

PictureBox Control
Displays graphics in bitmap, GIF, JPEG, metafile, or icon format.

PrintDialog Component
Selects a printer, chooses the pages to print, and determines other print-related settings.

PrintDocument Component
Sets the properties that describe what to print, and prints the document in Windows-based applications.

PrintPreviewControl Control
Allows you to create your own PrintPreview component or dialog box instead of using the pre-configured version.

PrintPreviewDialog Control
Displays a document as it will appear when it is printed.

ProgressBar Control
Graphically indicates the progress of an action towards completion.

RadioButton Control
Presents a set of two or more mutually exclusive options to the user.

RichTextBox Control
Allows users to enter, display, and manipulate text with formatting.

SaveFileDialog Component
Selects files to save and where to save them.

SoundPlayer Class Enables you to easily include sounds in your applications.

SplitContainer Control
Allows the user to resize a docked control.

Splitter Control
Allows the user to resize a docked control (.NET Framework version 1.x).

StatusBar Control
Displays status information related to the control that has focus. Although StatusStrip replaces and extends the StatusBar control of previous versions, StatusBar is retained for both backward compatibility and future use if you choose.

StatusStrip Control
Represents a Windows status bar control. Although StatusStrip replaces and extends the StatusBar control of previous versions, StatusBar is retained for both backward compatibility and future use if you choose.

TabControl Control
Displays multiple tabs that can contain pictures or other controls.

TableLayoutPanel Control
Represents a panel that dynamically lays out its contents in a grid composed of rows and columns.

TextBox Control
Allows editable, multiline input from the user.

Timer Component
Raises an event at regular intervals.

ToolBar Control
Displays menus and bitmapped buttons that activate commands. You can extend the functionality of the control and modify its appearance and behavior. Although ToolStrip replaces and adds functionality to the ToolBar control of previous versions, ToolBar is retained for both backward compatibility and future use if you choose.

ToolStrip Control
Creates custom toolbars and menus in your Windows Forms applications. Although ToolStrip replaces and adds functionality to the ToolBar control of previous versions, ToolBar is retained for both backward compatibility and future use if you choose.

ToolStripContainer Control
Provides panels on each side of a form for docking, rafting, and arranging ToolStrip controls, and a central ToolStripContentPanel for traditional controls.

ToolStripPanel Control
Provides one panel for docking, rafting and arranging ToolStrip controls.

ToolStripProgressBar Control Overview
Graphically indicates the progress of an action towards completion. The ToolStripProgressBar is typically contained in a StatusStrip.

ToolTip Component
Displays text when the user points at other controls.

TrackBar Control
Allows navigation through a large amount of information or visually adjusting a numeric setting.

TreeView Control
Displays a hierarchy of nodes that can be expanded or collapsed.

WebBrowser Control
Hosts Web pages and provides Internet Web browsing capabilities to your application.

Windows Forms Controls Used to List Options
Describes a set of controls used to provide users with a list of options to choose from.

Windows Forms Controls
Explains the use of Windows Forms controls, and describes important concepts for working with them.

Developing Windows Forms Controls at Design Time
Provides links to step-by-step topics, recommendations for which kind of control to create, and other information about creating your own control.

Controls and Programmable Objects Compared in Various Languages and Libraries
Provides a table that maps controls in Visual Basic 6.0 to the corresponding control in Visual Basic .NET. Note that controls are now classes in the .NET Framework.

How to: Add ActiveX Controls to Windows Forms
Describes how to use ActiveX controls on Windows Forms.

Читайте также:  Как ускорить postgresql 1c windows
Оцените статью