...Technology Simplified

Friday, April 20, 2012

Printer status in c#

No comments :
Add references for system.management from .Net dlls.
using System.Collections.Specialized; 
using System.Management;
#region GetPrintJobsCollection
        ///  
        /// Returns the jobs in printer queue 
        ///  
        /// Printer Name. 
        /// StringCollection 
        public StringCollection GetPrintJobsCollection(string printerName) 
        { 
            StringCollection printJobCollection = new StringCollection(); 
            try 
            { 
                //Query the printer to get the files waiting to print. 
                string searchQuery = "SELECT * FROM Win32_PrintJob";
                ManagementObjectSearcher searchPrintJobs = new ManagementObjectSearcher(searchQuery); 
                ManagementObjectCollection prntJobCollection = searchPrintJobs.Get();

                foreach (ManagementObject prntJob in prntJobCollection) 
                { 
                    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 prnName = jobName.Split(splitArr)[0]; 
                    string documentName = prntJob.Properties["Document"].Value.ToString(); 
                    if (String.Compare(prnName, printerName, true) == 0) 
                    { 
                        printJobCollection.Add(documentName); 
                    } 
                } 
            } 
            catch (Exception ex) 
            { 
                // Log the exception. 
            } 
            return printJobCollection; 
        }
        #endregion GetPrintJobsCollection
The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.
string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection coll = searcher.Get();

foreach (ManagementObject printer in coll)
{
    foreach (PropertyData property in printer.Properties)
    {
        Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
    }
}

No comments :

Post a Comment