c# 实现打印机状态查询与阻塞打印
作者:code2roc
这篇文章主要介绍了c# 引用System.Management来实现对打印机状态的查询,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下
在使用winform编写自动打印服务的过程中,发现只要进行了打印命令的调用,文档就会进入到打印等待队列,如果打印机无法正常工作,则会影响到相关业务数据的正确转换,所以需要检查打印机的状态来保障每次打印时打印机处于空闲状态,打印时队列中也只能有一个文档,本文是通过引用System.Management来实现对打印机状态的查询
打印机状态获取
enum PrinterStatus { 其他 = 1, 未知 = 2, 空闲 = 3, 打印 = 4, 预热 = 5, 停止打印 = 6, 脱机 = 7, } /// <summary> /// 获取打印机的当前状态 /// </summary> /// <param name="PrinterDevice">打印机设备名称</param> /// <returns>打印机状态</returns> private static PrinterStatus GetPrinterPrinterStatus(string PrinterDevice) { PrinterStatus ret = 0; string path = @"win32_printer.DeviceId='" + PrinterDevice + "'"; ManagementObject printer = new ManagementObject(path); printer.Get(); ret = (PrinterStatus)Convert.ToInt32(printer.Properties["PrinterStatus"].Value); return ret; }
打印机脱机检查
public static bool CheckPrinter(string BindPrintName) { ManagementScope scope = new ManagementScope(@"\root\cimv2"); scope.Connect(); // Select Printers from WMI Object Collections ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer"); string printerName = ""; foreach (ManagementObject printer in searcher.Get()) { printerName = printer["Name"].ToString().ToLower(); if (printerName.IndexOf(BindPrintName.ToLower()) > -1) { //foreach (var property in printer.Properties) //{ // LogUtil.WriteLog(property.Name + ":" + property.Value); //} if (printer["WorkOffline"].ToString().ToLower().Equals("true")) { return false; } else { return true; } } } return false; }
打印机阻塞队列实现
这里主要是通过一个while循环来不停的获取打印机的状态,空闲时才会进行下一次打印,通过两个标志位来配合轮询的外部介入退出
FinishWait标志位是任务内部的标识,如果打印机检查到了错误状态则进行轮询退出
GlobalInfo.IsGlobalExist标志位是程序全局标识,如果界面上通知用户等待时间过长,可以进行人工手动干预退出
//检查打印机状态 if (!CheckPrinter(PrintName)) { throw new PrintCheckException("打印机处于脱机状态"); } PrinterStatus State = GetPrinterPrinterStatus(PrintName); if (State == PrinterStatus.空闲) { } else if (State == PrinterStatus.打印 || State == PrinterStatus.预热) { //正在打印/预热时循环去查询打印机状态,如果变成了就绪就开始打印 while (State != PrinterStatus.空闲 && !FinishWait && !GlobalInfo.IsGlobalExist) { State = GetPrinterPrinterStatus(PrintName); if (!CheckPrinter(PrintName)) { FinishWait = true; throw new PrintCheckException("打印机处于脱机状态"); } if (State == PrinterStatus.打印 || State == PrinterStatus.预热 || State == PrinterStatus.空闲) { if (State == PrinterStatus.空闲) { FinishWait = true; } } else { FinishWait = true; throw new PrintCheckException("打印机状态错误,当前状态:" + State.ToString()); } }
以上就是c# 实现打印机状态查询与阻塞打印的详细内容,更多关于c# 打印机状态查询与阻塞打印的资料请关注脚本之家其它相关文章!