您好,登錄后才能下訂單哦!
這篇文章主要介紹“如何用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。