- How to: View Multiple Lines in the Windows Forms TextBox Control
- To display a carriage return in the TextBox control
- To view multiple lines in the TextBox control
- Controls to Use on Windows Forms
- In This Section
- Related Sections
- Как создать Windows Forms приложение из командной строки How to: Create a Windows Forms application from the command line
- Процедура Procedure
- Создание формы To create the form
- Компиляция и запуск приложения To compile and run the application
- Добавление элемента управления и обработка события Adding a control and handling an event
- Объявление элемента управления типа «Кнопка» и обработка событий щелчка мышью для нее To declare a button control and handle its click event
- Пример Example
How to: View Multiple Lines in the Windows Forms TextBox Control
By default, the Windows Forms TextBox control displays a single line of text and does not display scroll bars. If the text is longer than the available space, only part of the text is visible. You can change this default behavior by setting the Multiline, WordWrap, and ScrollBars properties to appropriate values.
To display a carriage return in the TextBox control
To display a carriage return in a multi-line TextBox, use the NewLine property.
Be aware that the interpretation of escape characters (\) is language-specific. Visual Basic uses Chr$(13) & Chr$(10) for the carriage return and linefeed character combination.
To view multiple lines in the TextBox control
Set the Multiline property to true . If WordWrap is true (the default), then the text in the control will appear as one or more paragraphs; otherwise it will appear as a list, in which some lines may be clipped at the edge of the control.
Set the ScrollBars property to an appropriate value.
Value | Description |
---|---|
None | Use this value if the text will be a paragraph that almost always fits the control. The user can use the mouse pointer to move around inside the control if the text is too long to display all at once. |
Horizontal | Use this value if you want to display a list of lines, some of which may be longer than the width of the TextBox control. |
Both | Use this value if the list may be longer than the height of the control. |
Set the WordWrap property to an appropriate value.
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.
Related Sections
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.
Как создать Windows Forms приложение из командной строки How to: Create a Windows Forms application from the command line
В процедурах ниже описаны основные шаги, которые необходимо выполнить для создания и запуска приложения Windows Forms из командной строки. The following procedures describe the basic steps that you must complete to create and run a Windows Forms application from the command line. Visual Studio предлагает расширенную поддержку этих процедур. There is extensive support for these procedures in Visual Studio. См. также раздел Пошаговое руководство. размещение элемента управления Windows Forms в WPF. Also see Walkthrough: Hosting a Windows Forms Control in WPF.
Процедура Procedure
Создание формы To create the form
В пустом файле кода введите следующую Imports using инструкцию или: In an empty code file, type the following Imports or using statements:
Объявите класс с именем Form1 , наследуемый от класса Form: Declare a class named Form1 that inherits from the Form class:
Создайте конструктор без параметров для Form1 . Create a parameterless constructor for Form1 .
В следующий процедуре будет добавлен дополнительный код конструктора. You will add more code to the constructor in a subsequent procedure.
Добавьте в класс метод Main . Add a Main method to the class.
Примените STAThreadAttribute к Main методу C#, чтобы указать Windows Forms приложение является однопотоковым апартаментом. Apply the STAThreadAttribute to the C# Main method to specify your Windows Forms application is a single-threaded apartment. (Атрибут не является обязательным в Visual Basic, так как приложения Windows Forms, разработанные с помощью Visual Basic, по умолчанию используют модель апартамента с одним потоком.) (The attribute is not necessary in Visual Basic, since Windows forms applications developed with Visual Basic use a single-threaded apartment model by default.)
Вызовите EnableVisualStyles , чтобы применить стили операционной системы к приложению. Call EnableVisualStyles to apply operating system styles to your application.
Создайте экземпляр формы и запустите его. Create an instance of the form and run it.
Компиляция и запуск приложения To compile and run the application
В командной строке .NET Framework перейдите к папке, в которой содержится класс Form1 . At the .NET Framework command prompt, navigate to the directory you created the Form1 class.
Скомпилируйте форму. Compile the form.
Если используется C#, введите: csc form1.cs If you are using C#, type: csc form1.cs
При использовании Visual Basic введите: vbc form1.vb If you are using Visual Basic, type: vbc form1.vb
В командной строке введите следующий текст: Form1.exe . At the command prompt, type: Form1.exe
Добавление элемента управления и обработка события Adding a control and handling an event
В предыдущей процедуре продемонстрировано, как создать простейшую форму Windows Forms, скомпилировать и запустить ее. The previous procedure steps demonstrated how to just create a basic Windows Form that compiles and runs. В следующей процедуре будет показано, как создать и добавить в форму элемент управления и как обрабатывать событие для него. The next procedure will show you how to create and add a control to the form, and handle an event for the control. Дополнительные сведения об элементах управления, которые можно добавить в Windows Forms, см. в разделе элементы управления Windows Forms. For more information about the controls you can add to Windows Forms, see Windows Forms Controls.
Помимо понимания способов создания приложений Windows Forms, следует обладать общими знаниями о программировании на основе событий и способах обработки данных, введенных пользователем. In addition to understanding how to create Windows Forms applications, you should understand event-based programming and how to handle user input. Дополнительные сведения см. в статьях Создание обработчиков событий в Windows Formsи обработка входных данных пользователя . For more information, see Creating Event Handlers in Windows Forms, and Handling User Input
Объявление элемента управления типа «Кнопка» и обработка событий щелчка мышью для нее To declare a button control and handle its click event
Объявите элемент управления типа «Кнопка» с именем button1 . Declare a button control named button1 .
В конструкторе создайте кнопку и задайте ее свойства Size, Location и Text. In the constructor, create the button and set its Size, Location and Text properties.
Добавьте кнопку в форму. Add the button to the form.
В следующем примере кода показано, как объявить элемент управления Button: The following code example demonstrates how to declare the button control:
Создайте метод для обработки события Click для кнопки. Create a method to handle the Click event for the button.
В обработчике событий щелчка мышью выведите элемент управления MessageBox с сообщением «Здравствуй, мир». In the click event handler, display a MessageBox with the message, «Hello World».
В следующем примере кода показано, как обрабатывается событие Click элемента управления Button: The following code example demonstrates how to handle the button control’s click event:
Свяжите событие Click с созданным методом. Associate the Click event with the method you created.
В примере кода ниже показано, как связать событие с методом. The following code example demonstrates how to associate the event with the method.
Скомпилируйте и запустите приложение, как описано в предыдущей процедуре. Compile and run the application as described in the previous procedure.
Пример Example
В следующем примере кода приведен полный пример из предыдущих процедур. The following code example is the complete example from the previous procedures: