using System.Windows.Forms; public class MainForm : Form { private Button btn1; public MainForm() { //Create the button btn1 = new Button(); btn1.Text = "Click me!"; //Set the text on the button //Add the button to the form Controls.Add(btn1); } }
private void btn1_Click(object sender, EventArgs e) { MessageBox.Show("Button clicked!"); } public MainForm() { btn1 = new Button(); btn1.Text = "Click me!"; btn1.Click += new EventHandler(btn1_Click); //Handle the Click event Controls.Add(btn1); }In this example, we handle the Click event of the button by adding a new event handler function. When the button is clicked, the function displays a message box. The package library for the System.Windows.Forms.Button class is the .NET Framework Class Library.