Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать
Figure 76 Press the Tab key one more time and Visual Studio 2008 inserts the - фото 126

Figure 7-6

Press the Tab key one more time, and Visual Studio 2008 inserts the stub of the event handler for you (see Figure 7-7).

Figure 77 The completed code looks like this public Form1 - фото 127

Figure 7-7

The completed code looks like this:

public Form1() {

InitializeComponent();

this.button1.Click += new EventHandler(button1_Click);

}

void button1_Click(object sender, EventArgs e) {

}

Notice thatClick is the event and the event handler must match the signature required by the event (in this case, the event handler for the Clickevent must have two parameter — objectand EventArgs). By convention, event handlers in the .NET Framework return void and have two parameters. The first is the source of the event (that is, the object that raises this event), and the second is an object derived from EventArgs. The EventArgsparameter allows data to be passed from an event to the event handler. The EventArgsclass is discussed further later in this chapter.

Using the new lambda expressions in C# 3.0, the preceding event handler can also be written like this:

public Form1() {

InitializeComponent();

this.button1.Click += (object sender, EventArgs e) => {

MessageBox.Show("Button clicked!");

};

}

Handling Events

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

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

The following program shows how you can use the Timerclass 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 Timerclass by passing it a value. The value is the time interval (in milliseconds) between the Timerclass's firing (raising) of its Elapsedevent. You next wire the Elapsedevent with the event handler t_Elapsed, which displays the current time in the console window. The Start()method of the Timerclass activates the Timerobject so that it can start to fire the Elapsedevent. Because the event is fired every second, the console is essentially updating the time every second (see Figure 7-8).

C 2008 Programmers Reference - изображение 128

Figure 7-8

Another useful class that is available in the .NET Framework class library is the FileSystemWatcherclass (located in the System.IOnamespace). It watches the file system for changes and enables you to monitor these changes by raising events. For example, you can use the FileSystemWatcherclass 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 FileSystemWatcherclass 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 FileSystemWatcherclass by initializing its Pathand Filterproperties:

FileSystemWatcher fileWatcher = new FileSystemWatcher() {

Path = @"c:\", Filter = "*.txt"

};

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

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) {

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x