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

Использование элемента управления "Button"

Кнопки позволяют пользователям взаимодействовать с программой. Например, во многих диалоговых окнах есть кнопки "ОК" и "Отменить". Для отправки сведений, введенных в диалоговом окне, пользователи могут нажать кнопку "ОК". В противном случае они могут нажать кнопку "Отмена" для закрытия диалогового окна без отправки данных.

Можно установить свойства для изменения ее внешнего вида. Например, можно установить свойство Text для отображения на кнопке определенного текста или свойство ForeColor для изменения цвета текста.

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

To use buttons in a program

  1. On the File menu, click NewProject.

  2. In the New Project dialog box, in the Templates pane, click Windows Forms Application.

  3. In the Name box, type ButtonExample, and then click OK.

A new Windows Forms project opens.

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

  2. In the Properties window, change the Text property to read: Display Date and then press ENTER.

  3. In the Properties window, click the drop-down arrow to the right of the ForeColor property, and then click the Custom tab of the dialog box that opens.

  4. Click the red box to apply red font to the text of the button.

  5. In the form, double-click the button to open the Code Editor.

The Code Editor opens in the middle of a method named button1_Click. This is the Click event handler. The code you write here will execute when the button is clicked.

  1. In the button1_Click event handler, type the following line of code.

    MessageBox.Show("Today is " +

    DateTime.Today.ToLongDateString());

  2. Press F5 to run your program.

  3. The program starts and the form appears. When you click the Button, a message box displays today's date.

Использование кнопок в программе

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

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

  3. В окне Имя введите ButtonExample и нажмите кнопку ОК.

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

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

  2. В окне Свойства измените свойство Text на Отобразить дату и затем нажмите клавишу ВВОД.

  3. Затем в окне Свойства щелкните стрелку раскрывающегося списка справа от свойства ForeColor, затем выберите вкладку Настраиваемый в появившемся диалоговом окне.

  4. Щелкните красный квадрат для использования красного шрифта в тексте на кнопке.

  5. В форме дважды щелкните кнопку, чтобы открыть редактор кода.

Редактор кода откроется в середине метода с именем button1_Click. Это — обработчик события Click. Вводимый здесь код будет выполняться при нажатии кнопки.

  1. В обработчик события button1_Click введите следующую строку кода.

    MessageBox.Show("Today is " +

    DateTime.Today.ToLongDateString());

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

  3. Программа запустится и появится форма. Если щелкнуть на Button, появляется окно сообщения, отображающее текущую дату.

How to: Call a Button's Click Event Programmatically

Even if a user does not click a button, you can raise the button's Click event programmatically by using the PerformClick method. The following example demonstrates how to call the click event of a button within a program. When button2 is clicked, the click event for button1 is also triggered.

To use buttons in a program

  1. On the File menu, click NewProject.

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

A new Windows Forms project opens.

  1. From the Toolbox, drag two Button controls onto the form.

  2. In the form, double-click the first button (button1) to create the Click event handler.

  3. In the button1_Click event handler, type the following line of code.

    MessageBox.Show("button1.Click was raised.");

  4. Right-click the code, and then click View Designer.

  5. Double-click the second button (button2) to create the Click event handler.

  6. In the button2_Click event handler, type the following line of code.

    // Call the Click event of button1.

    test.PerformClick();

  7. Press F5 to run the program.

  8. The program starts and the form appears. When you click either button1 or button2, the click event handler of button1 displays a message.

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