Cómo obtener Información de la Impresora in.NET?


En el PrintDialog estándar hay cuatro valores asociados con una impresora seleccionada: Estado, Tipo, Dónde y Comentario.

Si conozco el nombre de una impresora, ¿cómo puedo obtener estos valores en C# 2.0?

Author: John Saunders, 2008-11-17

8 answers

Como dowski sugirió, puede usar WMI para obtener las propiedades de la impresora. El siguiente código muestra todas las propiedades de un nombre de impresora determinado. Entre ellos se encuentran: PrinterStatus, Comment, Location, DriverName, PortName, etc.

using System.Management;

...

string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
    try
    {
        foreach (ManagementObject printer in coll)
        {
            foreach (PropertyData property in printer.Properties)
            {
                Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
            }
        }
    }
    catch (ManagementException ex)
    {
        Console.WriteLine(ex.Message);
    }
}
 64
Author: Panos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:51

Esto debería funcionar.

using System.Drawing.Printing;

...

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting

Después de eso, se pueden leer las diversas propiedades de PrinterSettings.

Tenga en cuenta que ps.isValid() puede ver si la impresora existe realmente.

Editar: Un comentario adicional. Microsoft recomienda usar un PrintDocument y modificar sus PrinterSettings en lugar de crear un PrinterSettings directamente.

 22
Author: Powerlord,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-17 17:42:47
 6
Author: John Sheehan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-17 17:32:44

Tenga en cuenta que el artículo que dowski y Panos se reffering a (MSDN Win32_Printer) puede ser un poco engañoso.

Me refiero al primer valor de la mayoría de los arrays. algunos comienzan con 1 y otros comienzan con 0. por ejemplo, " ExtendedPrinterStatus " el primer valor en la tabla es 1, por lo tanto, su matriz debe ser algo como esto:

string[] arrExtendedPrinterStatus = { 
    "","Other", "Unknown", "Idle", "Printing", "Warming Up",
    "Stopped Printing", "Offline", "Paused", "Error", "Busy",
    "Not Available", "Waiting", "Processing", "Initialization",
    "Power Save", "Pending Deletion", "I/O Active", "Manual Feed"
};

Y, por otro lado, "ErrorState" primer valor en la tabla es 0, por lo tanto, su matriz debe ser algo como esto:

string[] arrErrorState = {
    "Unknown", "Other", "No Error", "Low Paper", "No Paper", "Low Toner",
    "No Toner", "Door Open", "Jammed", "Offline", "Service Requested",
    "Output Bin Full"
};

POR cierto, "PrinterState " está obsoleto, pero puede usar " PrinterStatus".

 3
Author: itsho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-14 19:51:42

Solo como referencia, aquí hay una lista de todas las propiedades disponibles para un printer ManagementObject.

usage: printer.Properties["PropName"].Value
 3
Author: David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-13 22:28:17

Ha pasado mucho tiempo desde que he trabajado en un entorno Windows, pero le sugeriría que mire usando WMI.

 2
Author: dowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-17 17:23:09

Sé que es una publicación antigua, pero hoy en día la opción más fácil/rápida es usar los servicios de impresión mejorados ofrecidos por el marco WPF (utilizables por aplicaciones que no son WPF).

Http://msdn.microsoft.com/en-us/library/System.Printing (v=vs.110). aspx

Un ejemplo para recuperar el estado de la cola de impresión y el primer trabajo..

var queue = new LocalPrintServer().GetPrintQueue("Printer Name");
var queueStatus = queue.QueueStatus;
var jobStatus = queue.GetPrintJobInfoCollection().FirstOrDefault().JobStatus
 2
Author: stoj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-04 15:04:15

Como alternativa a WMI, puede obtener resultados rápidos y precisos tocando en WinSpool.drv (es decir, API de Windows): puede obtener todos los detalles de las interfaces, estructuras y constantes de pinvoke.net, o he puesto el código juntos en http://delradiesdev.blogspot.com/2012/02/accessing-printer-status-using-winspool.html

 0
Author: MarkMiddlemist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-27 12:43:44