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.
3. From the Toolbox, drag two Button controls onto the form.
4. In the form, double-click the first button (button1) to create the Click event handler.
5. In the button1_Click event handler, type the following line of code.
MessageBox.Show("button1.Click was raised."); |
6. Right-click the code, and then click View Designer.
7. Double-click the second button (button2) to create the Click event handler.
8. In the button2_Click event handler, type the following line of code.
// Call the Click event of button1. test.PerformClick(); |
9. Press F5 to run the program.
10. The program starts and the form appears. When you click either button1 or button2, the click event handler of button1 displays a message.
Программный вызов события нажатия кнопки
Даже если пользователь не нажимает кнопку, событие Click кнопки можно вызвать программным способом, воспользовавшись методом PerformClick. В следующем примере кода показан программный вызов события нажатия кнопки. При нажатии button1 также запускается событие нажатия для button2.
Использование кнопок в программе
1. В меню Файл выберите команду Создать проект.
2. В диалоговом окне Создание проекта в области Шаблоны выберите Приложение Windows Forms и нажмите кнопку ОК.
Откроется новый проект Windows Forms.
3. Из панели элементов перетащите в форму два элемента управления Button.
4. В форме дважды щелкните первую кнопку (button1), чтобы создать обработчик событий Click.
5. В обработчик событий button1_Click введите следующую строку кода.
MessageBox.Show("button1.Click was raised."); |
6. Правой клавишей мыши щелкните код и выберите команду Просмотреть конструктор.
7. Дважды щелкните вторую кнопку (button2), чтобы создать обработчик событий Click.
8. В обработчике событий button2_Click введите следующую строку кода.
// Call the Click event of button1. test[2].PerformClick(); |
9. Нажмите клавишу F5 для выполнения программы.
10. Программа запустится и появится форма. При щелчке button1 или button2 обработчик событий "Click" button1 выведет сообщение.
Дата добавления: 2022-05-27; просмотров: 126;