Prev | Current Page 277 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

To illustrate the pain, we??™ll start with
some code in C# 1 and improve it in the next couple of sections. Listing 5.1 builds a
(very) simple form with a button and subscribes to three of the button??™s events.
static void LogPlainEvent(object sender, EventArgs e)
{
Console.WriteLine ("LogPlain");
}
static void LogKeyEvent(object sender, KeyPressEventArgs e)
{
Console.WriteLine ("LogKey");
}
static void LogMouseEvent(object sender, MouseEventArgs e)
{
Console.WriteLine ("LogMouse");
}
...
Button button = new Button();
button.Text = "Click me";
button.Click += new EventHandler(LogPlainEvent);
button.KeyPress += new KeyPressEventHandler(LogKeyEvent);
button.MouseClick += new MouseEventHandler(LogMouseEvent);
Form form = new Form();
form.AutoSize=true;
form.Controls.Add(button);
Application.Run(form);
The output lines in the three event handling methods are there to prove that the code
is working: if you press the spacebar with the button highlighted, you??™ll see that the
Click and KeyPress events are both raised; pressing Enter just raises the Click event;
clicking on the button raises the Click and MouseClick events. In the following sections
we??™ll improve this code using some of the C# 2 features.
Let??™s start by asking the compiler to make a pretty obvious deduction??”which delegate
type we want to use when subscribing to an event.


Pages:
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289