Introduction
This code will test whether a printer is connected to your system or not. It works with USB and network printers (haven't tested LPT printers yet).
Some printers (like my HP DeskJet 930c) is detected online even though I press the OFF button (as long as the power adaptor is switched ON). This is true, as the printer is able to switch on itself when the print queue is not empty. But if I switch off the power adaptor, then the printer cannot switch on itself, and Windows automatically adjusts the printer setting by checking the "Use Printer Offline" in the Printer Control Panel.
Same case with network printers. When I plug my network cable, Windows automatically unchecks the "Use Printer Offline", and when I unplug it, Windows rechecks the "Use Printer Offline". This is what my code detects, whether "Use Printer Offline" is actually checked or not.
using System;
using System.Management;
namespace zedilabs.com
{
class PrinterOffline
{
[STAThread]
static void Main(string[] args)
{
ManagementScope scope = new ManagementScope(@"\root\cimv2");
scope.Connect();
ManagementObjectSearcher searcher = new
ManagementObjectSearcher("SELECT * FROM Win32_Printer");
string printerName = "";
foreach (ManagementObject printer in searcher.Get())
{
printerName = printer["Name"].ToString().ToLower();
if (printerName.Equals(@"hp deskjet 930c"))
{
Console.WriteLine("Printer = " + printer["Name"]);
if (printer["WorkOffline"].ToString().ToLower().Equals("true"))
{
Console.WriteLine("Your Plug-N-Play printer is not connected.");
}
else
{
Console.WriteLine("Your Plug-N-Play printer is connected.");
}
}
}
}
}
}