8.17 Manage Print Jobs


Problem

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

Solution

Use Windows Management Instrumentation. 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.

Discussion

Windows Management Instrumentation 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. In order to use WMI, you need to add a reference to the System.Management.dll assembly.

The following code shows a Windows-based 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 button after selecting a job to change its status.

 using System; using System.Windows.Forms; using System.Management; using System.Collections; public class PrintQueueTest : System.Windows.Forms.Form {     private System.Windows.Forms.ListBox lstJobs;     private System.Windows.Forms.Button cmdRefresh;     private System.Windows.Forms.TextBox txtJobInfo;     private System.Windows.Forms.Button cmdPause;     private System.Windows.Forms.Button cmdResume;     private System.Windows.Forms.Label label1;     private System.Windows.Forms.Label label2;     // (Designer code omitted.)     private void PrintQueueTest_Load(object sender, System.EventArgs e) {              cmdRefresh_Click(null, null);     }     private void cmdRefresh_Click(object sender, System.EventArgs e) {              // Select all the outstanding print jobs.         string query = "SELECT * FROM Win32_PrintJob";         ManagementObjectSearcher jobQuery =            new ManagementObjectSearcher(query);         ManagementObjectCollection jobs = jobQuery.Get();         // Add the jobs in the queue to the list box.         lstJobs.Items.Clear();         txtJobInfo.Text = "";         foreach (ManagementObject job in jobs) {             lstJobs.Items.Add(job["JobID"]);         }     }     // 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 + "'";             ManagementObjectSearcher jobQuery =                new ManagementObjectSearcher(query);                        ManagementObjectCollection jobs = jobQuery.Get();             IEnumerator enumerator = jobs.GetEnumerator();             enumerator.MoveNext();             return (ManagementObject)enumerator.Current;         }catch (InvalidOperationException){             // the Current property of the enumerator is invalid             return null;         }     }     private void lstJobs_SelectedIndexChanged(object sender,        System.EventArgs e) {              ManagementObject job = GetSelectedJob();         if (job == null) {             txtJobInfo.Text = "";             return;         }         // Display job information.         string jobInfo = "Document: " + job["Document"].ToString();         jobInfo += Environment.NewLine;         jobInfo += "DriverName: " + job["DriverName"].ToString();         jobInfo += Environment.NewLine;         jobInfo += "Status: " + job["Status"].ToString();                     jobInfo += Environment.NewLine;         jobInfo += "Owner: " + job["Owner"].ToString();         jobInfo += Environment.NewLine;         jobInfo += "PagesPrinted: " +         job["PagesPrinted"].ToString();         jobInfo += Environment.NewLine;         jobInfo += "TotalPages: " + job["TotalPages"].ToString();         if (job["JobStatus"] != null) {             txtJobInfo.Text += Environment.NewLine;             txtJobInfo.Text += "JobStatus: " + job["JobStatus"].ToString();         }         if (job["StartTime"] != null) {             jobInfo += Environment.NewLine;             jobInfo += "StartTime: " + job["StartTime"].ToString();         }         txtJobInfo.Text = jobInfo;     }     private void cmdPause_Click(object sender, System.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.");         }     }     private void cmdResume_Click(object sender, System.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.");             }         }     } } 

The window for this application is shown in Figure 8.12.

click to expand
Figure 8.12: Retrieving information from the print queue.

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 an exception to be thrown.

Note  

Other WMI methods that 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 Microsoft Developer Network (MSDN) documentation at http://msdn.microsoft.com/library/en-us/wmisdk/wmi/computer_system_hardware_classes.asp .




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net