在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),请执行如下命令:
下载本文