0 Replies - 293 Views - Last Post: 16 December 2009 - 11:25 AM

#1 PsychoCoder   User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1660
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Check if a printer is offline or online

Posted 16 December 2009 - 11:25 AM

Description: Need a reference to System.Management NamespaceThis snippet checks to see whether the specified printer is online or offline using WMI
/// 
///method to check if a printer is online or offline
/// 
/// name of the Printer
/// 
public bool IsPrinterOnline(string printerName)
{
    string str = "";
    bool online = false;

    //set the scope of this search to the local machine
    ManagementScope scope = new ManagementScope(ManagementPath.DefaultPath);
    //connect to the machine
    scope.Connect();

    //query for the ManagementObjectSearcher
    SelectQuery query = new SelectQuery("select * from Win32_Printer");

    ManagementClass m = new ManagementClass("Win32_Printer");

    ManagementObjectSearcher obj = new ManagementObjectSearcher(scope, query);

    //get each instance from the ManagementObjectSearcher object
    using (ManagementObjectCollection printers = m.GetInstances())
        //now loop through each printer instance returned
        foreach (ManagementObject printer in printers)
        {
            //first make sure we got something back
            if (printer != null)
            {
                //get the current printer name in the loop
                str = printer["Name"].ToString().ToLower();

                //check if it matches the name provided
                if (str.Equals(printerName.ToLower()))
                {
                    //since we found a match check it's status
                    if (printer["WorkOffline"].ToString().ToLower().Equals("true") || printer["PrinterStatus"].Equals(7))
                        //it's offline
                        online = false;
                    else
                        //it's online
                        online = true;
                }
            }
            else
                throw new Exception("No printers were found");
        }
    return online;
}


Is This A Good Question/Topic? 0
  • +

Page 1 of 1