Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
28
Добавлен:
23.11.2019
Размер:
2.4 Mб
Скачать

Создание непрямоугольной кнопки

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

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

В данном примере требуется проект приложения Windows Forms, содержащий форму с именем "Form2".

Пример

---

How to: Display Text on a Windows Form

You can display text on a variety of controls, but the primary control for displaying text in your program is the Label control. When you add a label to a form, the background appears in the same color as the form so that only the text is visible. You can also change the BackColor property of the label.

You can display text in the label by setting its Text property. The Font property determines the display font for the text in the Text property. The ForeColor property determines the color of the text itself.

To display text in a label

  1. On the File menu, click NewProject.

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

A new Windows Forms project opens.

  1. From the Toolbox, drag a Label onto the form.

  2. Add a Button control to the form, and change the following properties:

    Property

    Value

    Name

    changeText

    Text

    Change Text

    Size

    80, 23

  3. Double-click the button to create the changeText_Click event handler, and add the following code:

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

Отображение текста в форме Windows Forms

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

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

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

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

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

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

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

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

    Свойство

    Значение

    Имя

    changeText

    Текст

    Изменить текст

    Размер

    80, 23

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

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

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

    Property

    Value

    Name

    changeColor

    Text

    Change Color

    Size

    80, 23

  5. 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));

  6. Press F5 to run the program.

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

  8. 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.

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

    Свойство

    Значение

    Имя

    changeColor

    Текст

    Изменить цвет

    Размер

    80, 23

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

    Random randomColor = new Random();

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

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

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

  4. Нажмите кнопку Изменить текст и убедитесь, что текст в надписи обновлен.

  5. Нажмите кнопку Изменить цвет и убедитесь, изменился цвет шрифта текста.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]