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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

BeginPrint— Occurs when the Print()method is called and before the first page of the document prints. Typically, you use this event to initialize fonts, file streams, and other resources used during the printing process.

PrintPage— Occurs when the output to print for the current page is needed. This is the main event to code the logic required for sending the outputs to the printer.

EndPrint— Occurs when the last page of the document has printed. Typically, you use this event to release fonts, file streams, and other resources used during the printing process.

Adding Print Support to the Project

To add print support to the PhotoViewerapplication, first add the controls (see Figure 16-14) in the following table.

Control Text Name
Labelcontrols (2) Print from:
to
TextBoxcontrols (2) txtFrom
txtTo
Buttoncontrols (2) Preview btnPreview
Print btnPrint
Figure 1614 Switch to the codebehind of Form1 and import the following - фото 269

Figure 16-14

Switch to the code-behind of Form1, and import the following namespace:

using System.Drawing.Printing;

Declare the following member variables:

public partial class Form1 : Form {

//---constants for the icon images---

const int ico_OPEN = 0;

const int ico_CLOSE = 1;

const int ico_PHOTO = 2;

//---font variables---

Font f_title;

Font f_body;

//---page counter---

int pagecounter;

//---PrintDocument variable---

PrintDocument printDoc;

When the form is loaded during runtime, create an instance of the PrintDocument class, and wire up the three main event handlers described earlier:

private void Form1_Load(object sender, EventArgs e) {

printDoc = new PrintDocument() {

DocumentName = "Printing from Photo Viewer"

};

printDoc.BeginPrint += new PrintEventHandler(printDoc_BeginPrint);

printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);

printDoc.EndPrint += new PrintEventHandler(printDoc_EndPrint);

try {

//---load the application settings values

// into the textbox controls---

...

In the event handler for the BeginPrintevent, initialize the page counter as well as the fonts of the text to be used for printing the page:

void printDoc_BeginPrint(object sender, PrintEventArgs e) {

//---initialize the page counter---

pagecounter = int.Parse(txtFrom.Text);

//---initialize the fonts---

f_title = new Font("Arial", 16, FontStyle.Bold);

f_body = new Font("Times New Roman", 10);

}

In the EndPrint event handler, dereference the font variables used:

void printDoc_EndPrint(object sender, PrintEventArgs e) {

//---de-reference the fonts---

f_title = null;

f_body = null;

}

Finally, the event handler for PrintPageis the place where you do the bulk of the work of sending the output to the printer. Basically, you use the Graphicsobject in the PrintPageEventArgsclass to specify the output you want to print. For example, to draw a rectangle you would use the e.Graphics.DrawRectangle()method (where eis an instance of the PrintPageEventArgsclass). To print a string, you use the e.Graphics.DrawString()method. After printing, you increment the page count and determine if there are any more pages to print. If there are, setting the HasMorePagesproperty of the PrintPageEventArgsclass to true will cause the printDoc_PrintPageevent handler fire one more time. Once there are no more pages left to print, set the HasMorePagesproperty to false:

void printDoc_PrintPage(object sender, PrintPageEventArgs e) {

Graphics g = e.Graphics; //---draws the title---

g.DrawString(TreeView1.SelectedNode.Text, f_title, Brushes.Black, 20, 30);

//---draws a border...---

Rectangle border =

new Rectangle(10, 10,

PictureBox1.Width + 20, PictureBox1.Height + 60);

//---...using a thick pen---

Pen thickPen = new Pen(Color.Black, 3);

g.DrawRectangle(thickPen, border);

//---draws the picture---

if (PictureBox1.Image != null) {

g.DrawImage(PictureBox1.Image, 20, 60,

PictureBox1.Size.Width,

PictureBox1.Size.Height);

}

//---draws the page count---

g.DrawString("Page " + pagecounter, f_body, Brushes.Black, 20, 420);

//---increments the page counter---

pagecounter += 1;

//---determine if you have more pages to print---

if (pagecounter <= int.Parse(txtTo.Text)) e.HasMorePages = true;

else e.HasMorePages = false;

}

To let the user preview the output before the image is sent to the printer for printing, use the PrintPreviewDialog()class:

private void btnPreview_Click(object sender, EventArgs e) {

//---show preview---

PrintPreviewDialog dlg = new PrintPreviewDialog() {

Document = printDoc

};

dlg.ShowDialog();

}

This code previews the output in a separate window (see Figure 16-15). The user can click the printer icon to send the output to the printer. The user can also choose to enlarge the page or view multiple pages on one single screen.

Figure 1615 To print the image to a printer use the PrintDialogclass to let - фото 270

Figure 16-15

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

Интервал:

Закладка:

Сделать

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

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


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

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

x