Click here to Skip to main content
15,867,765 members
Articles / Programming Languages / C#

A Simple Approach for Controlling Print Jobs using WMI

Rate me:
Please Sign up or sign in to vote.
4.62/5 (24 votes)
1 Apr 20042 min read 252.8K   94   41
A simple approach for controlling print jobs using WMI

Introduction

This article presents a simplified approach of controlling print jobs using WMI. To know more about WMI, please visit MSDN.

Why WMI? Because it provides a simplified approach and avoids making API calls within our C# code. WMI comes as default for Windows XP and Windows 2000. For Windows 95/98, we need to download WMI Core 1.5 and install it: WMI Core 1.5

The Approach

First, let's see how to get the list of printers.

C#
public static StringCollection GetPrintersCollection()
{
    StringCollection printerNameCollection = new StringCollection();
    string searchQuery = "SELECT * FROM Win32_Printer";
    ManagementObjectSearcher searchPrinters = 
          new ManagementObjectSearcher(searchQuery);
    ManagementObjectCollection printerCollection = searchPrinters.Get();
    foreach(ManagementObject printer in printerCollection)
    {
        printerNameCollection.Add(printer.Properties["Name"].Value.ToString());
    }
    return printerNameCollection;
}

The above method returns the list of printers configured in the local machine. The printer ManagementObject exposes many useful properties. Using the PaperSizesSupported property, we can get the list of paper sizes supported by that particular printer. To view information about Win32_Printer, please refer to MSDN.

Using this printer name, we can fetch the print job collection by using the following method:

C#
public static StringCollection GetPrintJobsCollection(string printerName)
{
  StringCollection printJobCollection = new StringCollection();
  string searchQuery = "SELECT * FROM Win32_PrintJob";
  
  /*searchQuery can also be mentioned with where Attribute,
      but this is not working in Windows 2000 / ME / 98 machines 
      and throws Invalid query error*/
  ManagementObjectSearcher searchPrintJobs = 
            new ManagementObjectSearcher(searchQuery);
  ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();
  foreach(ManagementObject prntJob in prntJobCollection)
  {
    System.String jobName = prntJob.Properties["Name"].Value.ToString();

    //Job name would be of the format [Printer name], [Job ID]
    char[] splitArr = new char[1];
    splitArr[0] = Convert.ToChar(",");
    string prnterName = jobName.Split(splitArr)[0];
    string documentName = prntJob.Properties["Document"].Value.ToString();
    if(String.Compare(prnterName, printerName, true) == 0)
    {
      printJobCollection.Add(documentName);
    }
  }
  return printJobCollection;
}

The query "SELECT * FROM Win32_PrintJob" can also be used as "SELECT * FROM Win32_PrintJob WHERE Name like '"+ printerName.Replace("\", "\\") +"%'". But the query with WHICH attribute caused problems in my system which was running Windows 2000 but ran smooth in Windows XP machines. So currently, I am making a loop through all the print jobs and identify print jobs for that particular printer.

Now, let's see how to manage these print jobs. The print console provided by Windows allows us to Pause, Resume & Cancel print job. It also allows to set priority for a print job. Using WMI, we can perform Pause, Resume & Cancel, but it doesn't provide any method for changing the priority level.

The following code depicts how to pause a print job:

C#
public static bool PausePrintJob(string printerName, int printJobID)
{
  bool isActionPerformed = false;
  string searchQuery = "SELECT * FROM Win32_PrintJob";
  ManagementObjectSearcher searchPrintJobs = 
           new ManagementObjectSearcher(searchQuery);
  ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();
  foreach(ManagementObject prntJob in prntJobCollection)
  {
    System.String jobName = prntJob.Properties["Name"].Value.ToString();
    //Job name would be of the format [Printer name], [Job ID]
    char[] splitArr = new char[1];
    splitArr[0] = Convert.ToChar(",");
    string prnterName = jobName.Split(splitArr)[0];
    int prntJobID = Convert.ToInt32(jobName.Split(splitArr)[1]);
    string documentName = prntJob.Properties["Document"].Value.ToString();
    if(String.Compare(prnterName, printerName, true) == 0)
    {
      if(prntJobID == printJobID)
      {
        prntJob.InvokeMethod("Pause", null);
        isActionPerformed = true; 
        break;
      }
    }
  }
  return isActionPerformed;
}

By invoking the Pause method, we can pause the print job. Similar approach is required for resuming the print job. We just need to invoke the Resume method.

C#
prntJob.InvokeMethod("Resume", null);

Win32_PrintJob WMI_CLASS provides methods to pause and resume a print job. But it doesn't provide any method for cancelling the print job. To cancel the print job, you need to just delete the management object.

C#
public static bool CancelPrintJob(string printerName, int printJobID)
{
  bool isActionPerformed = false;
  string searchQuery = "SELECT * FROM Win32_PrintJob";
  ManagementObjectSearcher searchPrintJobs = 
         new ManagementObjectSearcher(searchQuery);
  ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();
  foreach(ManagementObject prntJob in prntJobCollection)
  {
    System.String jobName = prntJob.Properties["Name"].Value.ToString();
    //Job name would be of the format [Printer name], [Job ID]
    char[] splitArr = new char[1];
    splitArr[0] = Convert.ToChar(",");
    string prnterName = jobName.Split(splitArr)[0];
    int prntJobID = Convert.ToInt32(jobName.Split(splitArr)[1]);
    string documentName = prntJob.Properties["Document"].Value.ToString();
    if(String.Compare(prnterName, printerName, true) == 0)
    {
      if(prntJobID == printJobID)
      {
        //performs a action similar to the cancel 
        //operation of windows print console
        prntJob.Delete();
        isActionPerformed = true; 
        break;
      }
    }
  }
  return isActionPerformed;
}

That's it!

License

This article has no explicit license attached to it, but may contain usage terms in the article text or the download files themselves. If in doubt, please contact the author via the discussion board below. A list of licenses authors might use can be found here.


Written By
Web Developer
India India
My favourite quote "Temet Nosce" which means "Know Thyself". And I am working on that.

Comments and Discussions

 
QuestionDownloadable Example ? Pin
Gecko264812-Jul-06 12:33
Gecko264812-Jul-06 12:33 
AnswerRe: Downloadable Example ? Pin
SBendBuckeye17-Sep-13 5:27
SBendBuckeye17-Sep-13 5:27 
QuestionGet detail property printer Pin
Mohsen Ahmadian28-Sep-05 11:42
Mohsen Ahmadian28-Sep-05 11:42 
GeneralLog Printed Documents Pin
dboyko19-Aug-04 18:47
dboyko19-Aug-04 18:47 
GeneralMonitoring Pages Printed Pin
maraymer20-Jul-04 23:02
maraymer20-Jul-04 23:02 
GeneralRe: Monitoring Pages Printed Pin
Jagan Mohan21-Jul-04 18:05
Jagan Mohan21-Jul-04 18:05 
GeneralRe: Monitoring Pages Printed Pin
maraymer21-Jul-04 22:53
maraymer21-Jul-04 22:53 
GeneralRe: Monitoring Pages Printed Pin
Jayson Ragasa19-May-12 16:22
Jayson Ragasa19-May-12 16:22 
I'm also looking for this kind of solution. If you found one.. kindly please share it. Thanks!
Software Developer
Jayzon Ragasa
Baguio City, Philippines

GeneralWMI on remote machine !!! Pin
dharani23-Jun-04 6:09
dharani23-Jun-04 6:09 
GeneralRe: WMI on remote machine !!! Pin
Jagan Mohan23-Jun-04 18:15
Jagan Mohan23-Jun-04 18:15 
GeneralCan't delete.... Pin
Gizz14-Apr-04 3:52
Gizz14-Apr-04 3:52 
GeneralRe: Can't delete.... Pin
Tony Daems14-Apr-04 11:33
Tony Daems14-Apr-04 11:33 
GeneralRe: Can't delete.... Pin
Tony Daems14-Apr-04 12:04
Tony Daems14-Apr-04 12:04 
GeneralRe: Can't delete.... Pin
Tony Daems14-Apr-04 12:05
Tony Daems14-Apr-04 12:05 
GeneralRe: Can't delete.... Pin
Gizz14-Apr-04 21:29
Gizz14-Apr-04 21:29 
GeneralWHERE clause Pin
Fergal Boden7-Apr-04 23:05
Fergal Boden7-Apr-04 23:05 
GeneralRe: WHERE clause Pin
Jagan Mohan8-Apr-04 0:11
Jagan Mohan8-Apr-04 0:11 
GeneralSplit method has params overload Pin
rendle6-Apr-04 23:09
rendle6-Apr-04 23:09 
GeneralRe: Split method has params overload Pin
Jagan Mohan7-Apr-04 1:11
Jagan Mohan7-Apr-04 1:11 
GeneralRe: Split method has params overload Pin
rendle7-Apr-04 1:15
rendle7-Apr-04 1:15 
GeneralRe: Split method has params overload Pin
rendle7-Apr-04 2:17
rendle7-Apr-04 2:17 
GeneralRe: Split method has params overload Pin
Jagan Mohan7-Apr-04 18:46
Jagan Mohan7-Apr-04 18:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.