这篇文章主要介绍“如何用c#实现打印机脱机检查及阻塞打印”,在日常操作中,相信很多人在如何用c#实现打印机脱机检查及阻塞打印问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何用c#实现打印机脱机检查及阻塞打印”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
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 CollectionsManagementObjectSearcher 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#实现打印机脱机检查及阻塞打印”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。