![](https://img.51dongshi.com/20250108/wz/18400820952.jpg)
在Windows窗體應用程序中使用事件可以增強用戶交互性。例如,當用戶點擊Button控件時,該控件會觸發一個事件,應用程序可以針對這一按鈕點擊操作執行相應的邏輯。首先,您需要在窗體中添加一個Button控件。通過定義一個事件處理程序與Click事件委托簽名相匹配,您可以處理這一事件。這里使用的事件處理程序方法簽名應為void Button_Click(object sender, EventArgs e) {...}。接著,將事件處理程序方法添加到Button的Click事件中。這可以通過執行button.Click += new EventHandler(this.Button_Click)來實現。值得注意的是,設計工具如Visual Studio 2005可以自動生成類似上述代碼的事件連接代碼。下面的代碼示例展示了如何處理Button的Click事件以改變TextBox的背景色。在粗體標記的元素中,可以看到事件處理程序以及它如何與Button的Click事件相連。此示例僅包含基本編程元素,未使用可視化設計器。若使用設計器,它將生成附加代碼。以下是完整的示例代碼:using System;using System.ComponentModel;using System.Windows.Forms;using System.Drawing;public class MyForm : Form{private TextBox box;private Button button;public MyForm() : base(){box = new TextBox();box.BackColor = System.Drawing.Color.Cyan;box.Size = new Size(100,100);box.Location = new Point(50,50);box.Text = "Hello";button = new Button();button.Location = new Point(50,100);button.Text = "Click Me";// To wire the event, create a delegate instance and add it to the Click event.button.Click += new EventHandler(this.Button_Click);Controls.Add(box);Controls.Add(button);}// The event handler.private void Button_Click(object sender, EventArgs e){box.BackColor = System.Drawing.Color.Green;}// The STAThreadAttribute indicates that Windows Forms uses the single-threaded apartment model.[STAThreadAttribute]public static void Main(string[] args){Application.Run(new MyForm());}}完成上述步驟后,編譯并執行代碼。將上述代碼保存到一個文件中(對于C#文件,擴展名為.cs,對于Visual Basic 2005,擴展名為.vb),然后進行編譯和執行。例如,如果源文件名為WinEvents.cs(或WinEvents.vb),請執行如下命令: