Книга: C# 2008 Programmer

Handling Events

Handling Events

Let's take a look at how to handle events using a couple of simple examples. The Timer class (located in the System.Timers namespace) is a class that generates a series of recurring events at regular intervals. You usually use the Timer class to perform some background tasks, such as updating a ProgressBar control when downloading some files from a server, or displaying the current time.

The Timer class has one important event that you need to handle — Elapsed. The Elapsed event is fired every time a set time interval has elapsed.

The following program shows how you can use the Timer class to display the current time in the console window:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.Timers;
namespace Events {
 class Program {
  static void Main(string[] args) {
   Timer t = new Timer(1000);
   t.Elapsed += new ElapsedEventHandler(t_Elapsed);
   t.Start();
   Console.ReadLine();
  }
  static void t_Elapsed(object sender, ElapsedEventArgs e) {
   Console.SetCursorPosition(0, 0);
   Console.WriteLine(DateTime.Now);
  }
 }
}

First, you instantiate a Timer class by passing it a value. The value is the time interval (in milliseconds) between the Timer class's firing (raising) of its Elapsed event. You next wire the Elapsed event with the event handler t_Elapsed, which displays the current time in the console window. The Start() method of the Timer class activates the Timer object so that it can start to fire the Elapsed event. Because the event is fired every second, the console is essentially updating the time every second (see Figure 7-8).


Figure 7-8 

Another useful class that is available in the .NET Framework class library is the FileSystemWatcher class (located in the System.IO namespace). It watches the file system for changes and enables you to monitor these changes by raising events. For example, you can use the FileSystemWatcher class to monitor your hard drive for changes such as when a file/directory is deleted, is created, or has its contents changed.

To see how the FileSystemWatcher class works, consider the following program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;
using System.IO;
namespace Events {
 class Program {
  static void Main(string[] args) {
   FileSystemWatcher fileWatcher = new FileSystemWatcher() {
    Path = @"c:", Filter = "*.txt"
   };
   //---wire up the event handlers---
   fileWatcher.Deleted += new FileSystemEventHandler(fileWatcher_Deleted);
   fileWatcher.Renamed += new RenamedEventHandler(fileWatcher_Renamed);
   fileWatcher.Changed += new FileSystemEventHandler(fileWatcher_Changed);
   fileWatcher.Created += new FileSystemEventHandler(fileWatcher_Created);
   //---begin watching---
   fileWatcher.EnableRaisingEvents = true;
   Console.ReadLine();
  }
  static void fileWatcher_Created(object sender, FileSystemEventArgs e) {
   Console.WriteLine("File created: " + e.FullPath);
  }
  static void fileWatcher_Changed(object sender, FileSystemEventArgs e) {
   Console.WriteLine("File changed: " + e.FullPath);
  }
  static void fileWatcher_Renamed(object sender, RenamedEventArgs e) {
   Console.WriteLine("File renamed: " + e.FullPath);
  }
  static void fileWatcher_Deleted(object sender, FileSystemEventArgs e) {
   Console.WriteLine("File deleted: " + e.FullPath);
  }
 }
}

You first create an instance of the FileSystemWatcher class by initializing its Path and Filter properties:

FileSystemWatcher fileWatcher = new FileSystemWatcher() {
 Path = @"c:", Filter = "*.txt"
};

Here, you are monitoring the C: drive and all its files ending with the .txt extension.

You then wire all the events with their respective event handlers:

//---wire up the event handlers---
fileWatcher.Deleted += new FileSystemEventHandler(fileWatcher_Deleted);
fileWatcher.Renamed += new RenamedEventHandler(fileWatcher_Renamed);
fileWatcher.Changed += new FileSystemEventHandler(fileWatcher_Changed);
fileWatcher.Created += new FileSystemEventHandler(fileWatcher_Created);

These statements handle four events:

Deleted — Fires when a file is deleted

Renamed — Fires when a file is renamed

Changed — Fires when a file's content is changed

Created — Fires when a file is created

Finally, you define the event handlers for the four events:

static void fileWatcher_Created(object sender, FileSystemEventArgs e) {
 Console.WriteLine("File created: " + e.FullPath);
}
static void fileWatcher_Changed(object sender, FileSystemEventArgs e) {
 Console.WriteLine("File changed: " + e.FullPath);
}
static void fileWatcher_Renamed(object sender, RenamedEventArgs e) {
 Console.WriteLine("File renamed: " + e.FullPath);
}
static void fileWatcher_Deleted(object sender, FileSystemEventArgs e) {
 Console.WriteLine("File deleted: " + e.FullPath);
}

To test the program, you can create a new text file in C:drive, make some changes to its content, rename it, and then delete it. The output window will look like Figure 7-9.


Figure 7-9

Оглавление книги


Генерация: 0.910. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз