Tải bản đầy đủ - 0 (trang)
8-17. Show a Dynamic Print Preview

8-17. Show a Dynamic Print Preview

Tải bản đầy đủ - 0trang

CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



To use a stand-alone print preview form, you simply create a PrintPreviewDialog object, assign its

Document property, and call the Show method:

PrintPreviewDialog dlgPreview = new PrintPreviewDialog();

dlgPreview.Document = doc;

dlgPreview.Show();

The Print Preview window provides all the controls the user needs to move from page to page, zoom

in, and so on. The window even provides a print button that allows the user to send the document

directly to the printer. You can tailor the window to some extent by modifying the PrintPreviewDialog

properties.

You can also add a PrintPreviewControl control to any of your forms to show a preview alongside

other information. In this case, you do not need to call the Show method. As soon as you set the

PrintPreviewControl.Document property, the preview is generated. To clear the preview, set the Document

property to null, and to refresh the preview, simply reassign the Document property. PrintPreviewControl

shows only the preview pages, not any additional controls. However, you can add your own controls for

zooming, tiling multiple pages, and so on. You simply need to adjust the PrintPreviewControl properties

accordingly.



The Code

The following example is the complete for code that incorporates a PrintPreviewControl and allows the

user to select a zoom setting:

using

using

using

using



System;

System.Drawing;

System.Windows.Forms;

System.Drawing.Printing;



namespace Apress.VisualCSharpRecipes.Chapter08

{

public partial class Recipe08_17 : Form

{

public Recipe08_17()

{

InitializeComponent();

}

private PrintDocument doc;

// (PrintDocument.PrintPage event handler code omitted.

// See code in recipe 8-15.)

private void Recipe08_17_Load(object sender, EventArgs e)

{

// Set the allowed zoom settings.

for (int i = 1; i <= 10; i++)

{

lstZoom.Items.Add((i * 10).ToString());

}



411



www.it-ebooks.info



CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



// Create a document with 100 lines.

string[] printText = new string[100];

for (int i = 0; i < 100; i++)

{

printText[i] = i.ToString();

printText[i] += ": The quick brown fox jumps over the lazy dog.";

}

doc = new TextDocument(printText);

doc.PrintPage += this.Doc_PrintPage;

lstZoom.Text = "100";

printPreviewControl.Zoom = 1;

printPreviewControl.Document = doc;

printPreviewControl.Rows = 2;

}

private void cmdPrint_Click(object sender, EventArgs e)

{

// Set the zoom.

printPreviewControl.Zoom = Single.Parse(lstZoom.Text) / 100;

// Show the full two pages, one above the other.

printPreviewControl.Rows = 2;

// Rebind the PrintDocument to refresh the preview.

printPreviewControl.Document = doc;

}

}

// (TextDocument class code omitted. See recipe 8-15.)

}



8-18. Manage Print Jobs

Problem

You need to pause or resume a print job or a print queue.



Solution

Use Windows Management Instrumentation (WMI). You can retrieve information from the print queue

using a query with the Win32_PrintJob class, and you can use the Pause and Resume methods of the WMI

Win32_PrintJob and Win32_Printer classes to manage the queue.



412



www.it-ebooks.info



CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



How It Works

WMI allows you to retrieve a vast amount of system information using a query-like syntax. One of the

tasks you can perform with WMI is to retrieve a list of outstanding print jobs, along with information

about each one. You can also perform operations such as printing and resuming a job or all the jobs for a

printer. To use WMI, you need to add a reference to the System.Management.dll assembly.



The Code

The following code shows a Windows application that interacts with the print queue. It performs a WMI

query to get a list of all the outstanding jobs on the computer and displays the job ID for each one in a

list box. When the user selects the item, a more complete WMI query is performed, and additional

details about the print job are displayed in a text box. Finally, the user can click the Pause and Resume

buttons after selecting a job to change its status.

Remember that Windows permissions might prevent you from pausing or removing a print job

created by another user. In fact, permissions might even prevent you from retrieving status information

and could cause a security exception to be thrown.

using

using

using

using

using

using



System;

System.Drawing;

System.Windows.Forms;

System.Management;

System.Collections;

System.Text;



namespace Apress.VisualCSharpRecipes.Chapter08

{

public partial class Recipe08_18 : Form

{

public PrintQueueTest()

{

InitializeComponent();

}

private void cmdRefresh_Click(object sender, EventArgs e)

{

// Select all the outstanding print jobs.

string query = "SELECT * FROM Win32_PrintJob";

using (ManagementObjectSearcher jobQuery =

new ManagementObjectSearcher(query))

{

using (ManagementObjectCollection jobs = jobQuery.Get())

{

// Add the jobs in the queue to the list box.

lstJobs.Items.Clear();

txtJobInfo.Text = "";



413



www.it-ebooks.info



CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



foreach (ManagementObject job in jobs)

{

lstJobs.Items.Add(job["JobID"]);

}

}

}

}

private void Recipe08_18_Load(object sender, EventArgs e)

{

cmdRefresh_Click(null, null);

}

// This helper method performs a WMI query and returns the

// WMI job for the currently selected list box item.

private ManagementObject GetSelectedJob()

{

try

{

// Select the matching print job.

string query = "SELECT * FROM Win32_PrintJob " +

"WHERE JobID='" + lstJobs.Text + "'";

ManagementObject job = null;

using (ManagementObjectSearcher jobQuery =

new ManagementObjectSearcher(query))

{

ManagementObjectCollection jobs = jobQuery.Get();

IEnumerator enumerator = jobs.GetEnumerator();

enumerator.MoveNext();

job = (ManagementObject)enumerator.Current;

}

return job;

}

catch (InvalidOperationException)

{

// The Current property of the enumerator is invalid.

return null;

}

}

private void lstJobs_SelectedIndexChanged(object sender, EventArgs e)

{

ManagementObject job = GetSelectedJob();

if (job == null)

{

txtJobInfo.Text = "";

return;

}



414



www.it-ebooks.info



CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



// Display job information.

StringBuilder jobInfo = new StringBuilder();

jobInfo.AppendFormat("Document: {0}", job["Document"].ToString());

jobInfo.Append(Environment.NewLine);

jobInfo.AppendFormat("DriverName: {0}", job["DriverName"].ToString());

jobInfo.Append(Environment.NewLine);

jobInfo.AppendFormat("Status: {0}", job["Status"].ToString());

jobInfo.Append(Environment.NewLine);

jobInfo.AppendFormat("Owner: {0}", job["Owner"].ToString());

jobInfo.Append(Environment.NewLine);

jobInfo.AppendFormat("PagesPrinted: {0}", job["PagesPrinted"].ToString());

jobInfo.Append(Environment.NewLine);

jobInfo.AppendFormat("TotalPages: {0}", job["TotalPages"].ToString());

if (job["JobStatus"] != null)

{

txtJobInfo.Text += Environment.NewLine;

txtJobInfo.Text += "JobStatus: " + job["JobStatus"].ToString();

}

if (job["StartTime"] != null)

{

jobInfo.Append(Environment.NewLine);

jobInfo.AppendFormat("StartTime: {0}", job["StartTime"].ToString());

}

txtJobInfo.Text = jobInfo.ToString();

}

private void cmdPause_Click(object sender, EventArgs e)

{

if (lstJobs.SelectedIndex == -1) return;

ManagementObject job = GetSelectedJob();

if (job == null) return;

// Attempt to pause the job.

int returnValue = Int32.Parse(

job.InvokeMethod("Pause", null).ToString());

// Display information about the return value.

if (returnValue == 0)

{

MessageBox.Show("Successfully paused job.");

}

else

{

MessageBox.Show("Unrecognized return value when pausing job.");

}

}



415



www.it-ebooks.info



CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



private void cmdResume_Click(object sender, EventArgs e)

{

if (lstJobs.SelectedIndex == -1) return;

ManagementObject job = GetSelectedJob();

if (job == null) return;

if ((Int32.Parse(job["StatusMask"].ToString()) & 1) == 1)

{

// Attempt to resume the job.

int returnValue = Int32.Parse(

job.InvokeMethod("Resume", null).ToString());

// Display information about the return value.

if (returnValue == 0)

{

MessageBox.Show("Successfully resumed job.");

}

else if (returnValue == 5)

{

MessageBox.Show("Access denied.");

}

else

{

MessageBox.Show(

"Unrecognized return value when resuming job.");

}

}

}

}

}

Figure 8-10 shows the window for this application.



416



www.it-ebooks.info



CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



Figure 8-10. Retrieving information from the print queue



■ Note Other WMI methods you might use in a printing scenario include AddPrinterConnection,

SetDefaultPrinter, CancelAllJobs, and PrintTestPage, all of which work with the Win32_Printer class. For

more information about using WMI to retrieve information about Windows hardware, refer to the MSDN

documentation.



8-19. Perform Text-to-Speech

Problem

You need to read a piece of text aloud.



Solution

Create an instance of System.Speech.Synthesis.SpeechSynthesizer, contained in the System.Speech

assembly, and call the Speak instance method, passing in the string that you wish to be spoken.



417



www.it-ebooks.info



CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



How It Works

The SpeechSynthesizer class provides managed access to the Windows Speech SDK. Creating an

instance of SpeechSynthesizer allows you to have text spoken by passing a string to the Speak method.

The Speak method is synchronous, meaning that your application will pause until the speech has

completed—you can have text spoken aloud in the background by using the SpeakAsync method.

Windows provides support for having different voices read text. The voices available on your

machine will depend on the version of Windows you have installed and which other applications are

available—some Microsoft and third-party applications provide additional voices. You can get

information about the voices available by calling the SpeechSynthesizer.GetInstalledVoices instance

method, which returns an enumeration of System.Speech.Synthesis.InstalledVoice. You can select the

voice to use for speech with the SpeechSyntheizer.SelectVoice method. Other useful members of the

SpeechSynthesizer class are listed in Table 8-1.

Table 8-1. Useful Members of SpeechSynthesizer



Member



Description



GetInstalledVoices



Returns an enumeration of InstalledVoice



Pause



Pauses the synthesizer



Resume



Resumes the synthesizer playback



SelectVoice



Selects an installed synthesizer voice



SetOutputToWaveFile



Saves the synthesized speed to a sound file



Speak



Synchronously speaks a string



SpeakAsync



Asynchronously speaks a string



Rate



Returns the speed at which speech is performed



Volume



Returns the volume of the speech output



The Code

The following example displays information about each speech synthesis voice installed on the local

machine, and then enters a loop where lines of text read from the console are passed to the Speak

method of a SpeechSynthesizer instance.



418



www.it-ebooks.info



CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



■ Note You will need to add the System.Speech assembly as a reference to your Visual Studio project in order to

use the System.Speech.Synthesis namespace.



using

using

using

using

using



System;

System.Collections.Generic;

System.Linq;

System.Text;

System.Speech.Synthesis;



namespace Apress.VisualCSharpRecipes.Chapter08

{

class Recipe08_19

{

static void Main(string[] args)

{

// Create a new synthesizer.

SpeechSynthesizer mySynth = new SpeechSynthesizer();

Console.WriteLine("--- Start of voices list ---");

foreach (InstalledVoice voice in mySynth.GetInstalledVoices())

{

Console.WriteLine("Voice: {0}", voice.VoiceInfo.Name);

Console.WriteLine("Gender: {0}", voice.VoiceInfo.Gender);

Console.WriteLine("Age: {0}", voice.VoiceInfo.Age);

Console.WriteLine("Culture: {0}", voice.VoiceInfo.Culture);

Console.WriteLine("Description: {0}", voice.VoiceInfo.Description);

}

Console.WriteLine("--- End of voices list ---");

while (true)

{

Console.WriteLine("Enter string to speak");

mySynth.Speak(Console.ReadLine());

Console.WriteLine("Completed");

}

}

}

}



8-20. Recognize Characters in an Image (OCR)

Problem

You need to perform optical character recognition (OCR) to recognize words in an image.



419



www.it-ebooks.info



CHAPTER 8 ■ GRAPHICS, MULTIMEDIA, AND PRINTING



Solution

Use COM Interop to access the features of Microsoft Office Document Imaging.



■ Note This recipe requires Microsoft Office 2007.



How It Works

The first step is to install the Microsoft Office Document Imaging (MODI), which is not installed by

default by the Microsoft Office installation. Run the Office installer, and select Microsoft Office

Document Imaging from the Office Tools section, as shown in Figure 8-11.



Figure 8-11. Installing MODI



420



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

8-17. Show a Dynamic Print Preview

Tải bản đầy đủ ngay(0 tr)

×