Windows forms куда выводить текст

Обновлено: 05.07.2024

Отобразить текст можно в самых различных элементах управления, однако основным элементом в программе, в котором выводится текст, является Label. При добавлении надписи в форму цвет фона совпадет с цветом формы так, что виден только текст. Можно изменить свойство BackColor надписи.

Для отображения текста в надписи свойству Text следует задать определенное значение. Свойство Font определяет шрифт для отображения текста, содержащегося в свойстве Text. Свойство ForeColor определяет непосредственно цвет текста.

Отображение текста в надписи

В меню Файл выберите команду Создать проект .

В диалоговом окне Создание проекта выберите Приложение Windows Forms , а затем нажмите кнопку ОК .

Откроется новый проект Windows Forms.

Из панели элементов перетащите в форму элемент управления Label.

Добавьте элемент управления Button в форму и измените следующие свойства.

Дважды щелкните кнопку, чтобы создать обработчик событий changeText_Click, и добавьте следующий код.

this .label1.Text = "Time " + DateTime.Now.ToLongTimeString();

Add another Button control to the form, and change the following properties

Double-click the button to create the changeColor_Click event handler, and add the following code:

Random randomColor = new Random();

this .label1.ForeColor = Color.FromArgb(randomColor.Next(0, 256),

randomColor.Next(0, 256), randomColor.Next(0, 256));

Press F5 to run the program.

Click Change Text and verify that the text in the label is updated.

Click Change Color and verify that the font of the text is changed to a new color.

How to: Use TextBox Controls to Get User Input

You can both display text and retrieve text from users by using a TextBox control. After a user types data in a TextBox, you can retrieve this data by using the Text property. By default, the Multiline property of the TextBox is set to false . This means that users cannot press the ENTER key to create multiple lines of text in the TextBox. You can set the Multiline property to true to enable this.

Добавьте в форму другой элемент управления Button и измените следующие свойства.

Дважды щелкните кнопку, чтобы создать обработчик событий changeColor_Click, и добавьте следующий код.

Random randomColor = new Random();

this .label1.ForeColor = Color.FromArgb(randomColor.Next(0, 256),

randomColor.Next(0, 256), randomColor.Next(0, 256));

Нажмите клавишу F5 для выполнения программы.

Использование элемента управления "TextBox" для получения вводимых данных

С помощью элемента управления TextBox можно как отображать текст, так и получать его от пользователя. Введенные пользователем данные в TextBox можно получить с помощью свойства Text. По умолчанию свойство Multiline TextBox имеет значение false . Это означает, что пользователь не может нажимать клавишу ВВОД для создания нескольких строк текста в TextBox. Для включения этой возможности установите для свойства Multiline значение true .

To retrieve input typed in a text box

On the File menu, click NewProject .

In the New Project dialog box, click Windows Forms Application , and then click OK .

A new Windows Forms project opens.

From the Toolbox , drag a TextBox control onto the form, and change the following properties in the Properties window:

Add a Button control next to the text box, and change the following properties:

Double-click the button to create the retrieveInput_Click event handler, and add the following code:

MessageBox.Show( this .inputText.Text);

Press F5 to run the program.

Type multiple lines of text in the text box, and then click Retrieve .

Verify that the message displays all the text that you typed in the text box.

Извлечение введенных в текстовое поле данных

В меню Файл выберите команду Создать проект .

В диалоговом окне Создание проекта выберите Приложение Windows Forms , а затем нажмите кнопку ОК .

Откроется новый проект Windows Forms.

Перетащите элемент управления TextBox из панели элементов в форму и измените следующие свойства в окне Свойства .

Добавьте элемент управления Кнопка в форму и измените следующие свойства.

Дважды щелкните кнопку для создания обработчика событий retrieveInput_Click и добавьте следующий код.

MessageBox.Show( this .inputText.Text);

Нажмите клавишу F5 для выполнения программы.

Введите несколько строк текста в текстовом поле и нажмите кнопку Извлечь .

How to: Convert the Text in a TextBox Control to an Integer

When you provide a TextBox control in your application to retrieve a numeric value, you often have to convert the text (a string) to a numeric value, such as an integer. This example demonstrates two methods of converting text data to integer data.

Example
Compiling the Code

This example requires:

A TextBox control named textBox1 .

Robust Programming

The following conditions may cause an exception:

The text converts to a number that is too large or too small to store as an int .

The text may not represent a number.

Преобразование текста в элементе управления "TextBox" в целое число

Если в приложении используется элемент управления TextBox для извлечения числовых значений, часто приходится преобразовывать текст (строку) в числовое значение, например целое число. В этом примере показано два способа преобразования текстовых данных в целочисленные.

Пример
Компиляция кода 3

Для этого примера необходимы следующие компоненты.

Элемент управления TextBox с именем textBox1 .

Надежное программирование

Исключение может возникнуть при следующих условиях.

Текст преобразуется в число, которое слишком велико или мало для сохранения в качестве int .

Возможно, текст не представляет число.

How to: Set the Selected Text in a TextBox Control

This example programmatically selects text in a Windows Forms TextBox control and retrieves the selected text.

Example

private void button1_Click(object sender, EventArgs e)

textBox1.Text = "Hello World";

Compiling the Code

This example requires:

A form with a TextBox control named textBox1 and a Button control named button1 . Set the Click event handler of button1 to button1_Click.

The code can also be used with a RichTextBox control by substituting a RichTextBox control named richTextBox1 for the TextBox control and changing the code from textBox1 to richTextBox1.

Robust Programming

In this example you are setting the Text property before you retrieve the SelectedText value. In most cases, you will be retrieving text typed by the user. Therefore, you will want to add error-handling code in case the text is too short.

Установка выделения текста в элементе управления "TextBox"

В этом примере в элементе управления Windows Forms TextBox текст выделяется программным путем, а затем извлекается.

Пример

private void button1_Click(object sender, EventArgs e)

textBox1.Text = "Hello World";

Компиляция кода 4

Для этого примера необходимы следующие компоненты.

Форма с элементом управления TextBox с именем textBox1 и с элементом управления Button с именем button1 . Задайте обработчику событий Click для button1 значение button1_Click.

Код также можно использовать с элементом управления RichTextBox, заменив элемент управления TextBox на элемент управления RichTextBox с именем richTextBox1 и изменив в коде имя с textBox1 на richTextBox1.

Надежное программирование

В этом примере перед извлечением значения SelectedText устанавливается свойство Text. В большинстве случаев извлекается текст, введенный пользователем. Поэтому если текст слишком короток, в код рекомендуется добавить обработчик ошибок.

How to: Format Characters in a RichTextBox Control

This example writes a sentence, which contains three words in three different font styles (bold, italic, and underlined), to an existing RichTextBox control.

Example

@"this is in \i italics\i0, " +

@"and this is \ul underlined\ul0.>";

Compiling the Code

This example requires: A RichTextBox control named richTextBox1 .

Robust Programming

The rich text format is very flexible, but any errors in the format lead to errors in the displayed text.

Форматирование знаков в элементе управления "RichTextBox"

В этом примере выполняется запись предложения, содержащего три слова, написанных разными шрифтами (полужирным, курсивом и с подчеркиванием), в существующий элемент управления RichTextBox.

Пример

@"and this is \ul underlined\ul0.>";

Компиляция кода 5

Для этого примера необходимы следующие компоненты. Элемент управления RichTextBox с именем richTextBox.

Надежное программирование

Расширенный текстовый формат очень гибок, но любая ошибка в формате приведет к ошибкам в отображаемом тексте.

How to: Load Text into a RichTextBox Control

This example loads a text file that a user selects in the OpenFileDialog. The code then populates a RichTextBox control with the file's contents.

Example

// Create an OpenFileDialog object.

OpenFileDialog openFile1 = new OpenFileDialog();

// Initialize the filter to look for text files.

openFile1.Filter = "Text Files|*.txt";

// If the user selected a file, load its contents into the RichTextBox.

if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)

Compiling the Code

This example requires:

A RichTextBox control named richTextBox1. Insert the code segment into the Form1_Load method. When you run the program, you will be prompted to select a text file.

Загрузка текста в элемент управления "RichTextBox"

В этом примере выполняется загрузка текстового файла, выбранного пользователем в OpenFileDialog. Затем код заполняет элемент управления RichTextBox содержимым файла.

Пример

// Create an OpenFileDialog object.

OpenFileDialog openFile1 = new OpenFileDialog();

// Initialize the filter to look for text files.

openFile1.Filter = "Text Files|*.txt";

// If the user selected a file, load its contents into the RichTextBox.

if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)

Компиляция кода

Для этого примера необходимы следующие компоненты.

Элемент управления RichTextBox с именем richTextBox1. Вставьте сегмент кода в метод Form1_Load. 6 При выполнении программы будет выведен запрос на выбор текстового файла.

Dialog Boxes

How to: Retrieve Data from a Dialog Box

Dialog boxes enable your program to interact with users and retrieve data that users have entered in the dialog box for use in your application. There are several built-in dialog boxes that you can use in your applications. You can also create your own dialog boxes.

Диалоговые окна

Извлечение данных из диалогового окна

Диалоговые окна позволяют программе взаимодействовать с пользователями и извлекать данные, введенные ими в диалоговое окно, в приложение. Существует несколько встроенных, доступных для использования в приложениях, диалоговых окон. Можно также создавать свои собственные диалоговые окна.

To create the main form of your application

On the File menu, click New Project .

The New Project dialog box appears.

Click Windows Forms Application , and then click OK .

A form named Form1 is added to the project.

From the Toolbox , drag a ListBox control to the form, and change the following property in the Properties window:

Add a Button control to the form, and change the following properties in the Properties window:

Читайте также: