简体   繁体   中英

Check printer if connected to pc or not

I need to write some code that would prompt a message "printer is connected" when the printer is plugged into the computer and also prompt a message "printer not connected" when I plug out the printer from computer. I also want to list the printers available through a combobox . How can I do this in C# using Visual Studio?

You should use Winspool.lib

C# Signature :

[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);

EDIT:

You can also use this

foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
{
   //Add in combo box
}

to immediately get the pop-up that new Printer Found/Disconnected... you must have to run some code in background continuously Windows Service is the best for that.. and using the below code you can get the installed printer so first store the currently installed printer in list and after each 10(or any you want) second get the installed printer again if difference found propmt the message accordingly..

this is the snippet to get the installed printer..

private string[] GetAvailablePrinters()
{
    var installedPrinters = new string[PrinterSettings.InstalledPrinters.Count];
    PrinterSettings.InstalledPrinters.CopyTo(installedPrinters, 0);

    var printers = new List<string>();
    var printServers = new List<string>();
    var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");

    foreach (var printer in searcher.Get())
    {
        var serverName = @"\\" + printer["SystemName"].ToString().TrimStart('\\');
        if (!printServers.Contains(serverName))
            printServers.Add(serverName);
    }

    foreach (var printServer in printServers)
    {
        var server = new PrintServer(printServer);
        try
        {
            var queues = server.GetPrintQueues();
            printers.AddRange(queues.Select(q => q.Name));
        }
        catch (Exception)
        {
            // Handle exception correctly
        }
    }

    return printers.ToArray();
}

You might need to add the System.Management, System.Drawing, System.Printing references in you project..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM