public void Print(ref FrameworkElement fwe) { if (TransactionData == null) { return; } //LocalPrintServer printserver = new LocalPrintServer(); PrintServer printserver = new PrintServer(Station.PrintServer); Size visualSize; visualSize = new Size(288, 2 * 96);// paper size DrawingVisual visual = PrintControlFactory.CreateDrawingVisual(fwe, fwe.ActualWidth, fwe.ActualHeight); SUT.PrintEngine.Paginators.VisualPaginator page = new SUT.PrintEngine.Paginators.VisualPaginator(visual, visualSize, new Thickness(0, 0, 0, 0), new Thickness(0, 0, 0, 0)); page.Initialize(false); PrintDialog pd = new PrintDialog(); pd.PrintQueue = printserver.GetPrintQueue(Station.ReceiptPrinterName); // pd.PrintQueue = printserver.GetPrintQueue("TSC TDP-244"); // pd.PrintQueue = printServer.GetPrintQueues(new [] {EnumeratedPrintQueueTypes.Shared} ); //if (pd.ShowDialog()==true) //{ pd.PrintDocument(page, ""); //} }
private static PrintQueue SelectedPrintServer(string printerName) { try { var printers = PrinterSettings.InstalledPrinters;//获取本机上的所有打印机 PrintServer printServer = null; foreach (string printer in printers) { if (printer.Contains(printerName)) { printServer = new PrintServer(PrintSystemDesiredAccess.AdministrateServer); } } if (printServer == null) { return(null); //没有找到打印机服务器 } var printQueue = printServer.GetPrintQueue(printerName); return(printQueue); } catch (Exception ex) { return(null);//没有找到打印机 } }
private void BwPerformPrint(object sender, DoWorkEventArgs e) { var ps = new PrintServer(); PrintQueueCollection myPrintQueues = ps.GetPrintQueues(); //Lấy máy in để xử lý trạng thái try { while (dtPrintingStatus.Rows.Count > 0) { PrintQueue printer = (from m in myPrintQueues where m.Name.Equals(dtPrintingStatus.Rows[0]["PrinterName"].ToString()) select m).FirstOrDefault(); if (CheckPrinterStatus(printer)) { PerformPrint(); } else { //Dừng 4s rồi tiếp tục kiểm tra việc in Thread.Sleep(4000); } } dsPrinting.Clear(); } catch (Exception ex) { Utility.ShowMsg(ex.Message); } }
public object GetPrinters() { var resultado = new List <object>(); //foreach (var NombrePrinter in System.Drawing.Printing.PrinterSettings.InstalledPrinters) //{ // resultado.Add(new { DisplayText = NombrePrinter, Value = NombrePrinter }); //} var server = new PrintServer(); var locales = server.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }); foreach (var printer in locales) { resultado.Add(new { DisplayText = printer.FullName, Value = printer.FullName }); } var compartidos = server.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Shared, EnumeratedPrintQueueTypes.Connections }); foreach (var printer in locales) { if (locales.SingleOrDefault(s => s.FullName == printer.FullName) == null) { resultado.Add(new { DisplayText = printer.FullName, Value = printer.FullName }); } } return(new { Result = "OK", Options = resultado }); }
private static void timer_Elapsed(object sender, ElapsedEventArgs e) { try { // Console.WriteLine("L"); PrintServer ps = new PrintServer(); // PrintServer ps = new PrintServer(System.Printing.PrintSystemDesiredAccess.AdministrateServer); // PrintQueueCollection pQueue = ps.GetPrintQueues(); PrintQueueCollection pQueue = ps.GetPrintQueues(); // new PrintQueue(ps, printer.printer_name, PrintSystemDesiredAccess.AdministratePrinter) int x = 1; foreach (PrintQueue pq in pQueue) { // Console.WriteLine(pq.Name); foreach (var job in ps.GetPrintQueue(pq.Name).GetPrintJobInfoCollection()) { job.Pause(); // Console.WriteLine("Paused - " + job.Name); } // Console.WriteLine("----"); } } catch (Exception ex) { } }
static public void PrintDoc2(PrintDocArgs Args, int TryCount) { int W = 268; //268 double H = 5000; ctrlCheckVisual vis = new ctrlCheckVisual(); if (Args.FStrs != null) { BitmapImage QrImg = FiscalCheckCreator.CreateQRBitmap(Args.QRAsStr, 130, 130); vis.CreateCheck(Args.FStrs, QrImg); vis.Visibility = Visibility.Visible; // string PrName = @"Predchek4"; string PrName = iniFile.FRSPrinterName; try { Utils.ToCardLog("PrintDoc PrName " + PrName); PrintDialog Pd = new PrintDialog(); Pd.PageRangeSelection = PageRangeSelection.AllPages; PrintServer Ps = new PrintServer(); PrintQueue PQ = new PrintQueue(Ps, PrName); Pd.PrintQueue = PQ; // Pd.ShowDialog(); PrintTicket Pt = Pd.PrintTicket; Pt.PageMediaSize = new PageMediaSize(W, 11349); Pt.PageBorderless = PageBorderless.Borderless; Pt.PageResolution = new PageResolution(203, 203); Pt.PageScalingFactor = 1; Pt.TrueTypeFontMode = TrueTypeFontMode.DownloadAsRasterFont; Size pageSize = new Size(W - 10, Pd.PrintableAreaHeight); //pageSize = new Size(W, H); ((UserControl)vis).Measure(pageSize); ((UserControl)vis).Arrange(new Rect(0, 0, W - 10, ((UserControl)vis).Height)); //((UserControl)vis).Arrange(new Rect(0, 0, W, H)); if (iniFile.FRSSaveCheckToImg2) { SaveCheckVisualToFile(vis, W, Convert.ToInt32(((UserControl)vis).Height)); } Pd.PrintVisual(vis, "Hello"); Ps.Dispose(); Pd.PrintQueue.Dispose(); Pd = null; QrImg = null; } catch (Exception e) { Utils.ToCardLog("PrintDoc Error " + e.Message); if (TryCount < 5) { Utils.ToCardLog("Try again " + TryCount); System.Threading.Thread.Sleep(300); GC.Collect(); PrintDoc2(Args, TryCount + 1); } } } vis = null; GC.Collect(); }
private void button1_Click(object sender, RoutedEventArgs e) { #region #xpfprinter RichEditDocumentServer srv = new RichEditDocumentServer(); srv.LoadDocument("test.docx"); FixedDocument document = RichEditDocumentXpfPrinter.CreateFixedDocument(srv); PrintDialog pDialog = new PrintDialog(); PrintQueueCollection queues = new PrintServer().GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }); System.Collections.IEnumerator localPrinterEnumerator = queues.GetEnumerator(); PrintQueue printQueue = null; do { if (!localPrinterEnumerator.MoveNext()) { break; } printQueue = (PrintQueue)localPrinterEnumerator.Current; }while (!printQueue.FullName.Contains("Canon")); if (printQueue != null) { pDialog.PrintQueue = printQueue; pDialog.PrintDocument(document.DocumentPaginator, string.Empty); } #endregion #xpfprinter }
private static PrintQueue GetMicrosoftPdfPrintQueue() { PrintQueue pdfPrintQueue = null; try { using (var printServer = new PrintServer()) { var flags = new[] { EnumeratedPrintQueueTypes.Local }; pdfPrintQueue = printServer.GetPrintQueues(flags).SingleOrDefault(lq => lq.QueueDriver.Name == PdfPrinterDriveName); } if (pdfPrintQueue == null) { throw new Exception($"Could not find printer with driver name: {PdfPrinterDriveName}"); } if (!pdfPrintQueue.IsXpsDevice) { throw new Exception($"PrintQueue '{pdfPrintQueue.Name}' does not understand XPS page description language."); } return(pdfPrintQueue); } catch { pdfPrintQueue?.Dispose(); throw; } }
/// <summary> /// Get the model name of printer. /// </summary> /// <returns> /// If success, return the name of printer driver, otherwise, return empty string. /// </returns> public static bool GetPrinterDrvName( string strPrinterName, ref string strDrvName ) { strDrvName = ""; bool bSuccess = false; try { PrintServer myPrintServer = new PrintServer(null); PrintQueueCollection myPrintQueues = myPrintServer.GetPrintQueues(); foreach (PrintQueue pq in myPrintQueues) { if (strPrinterName == pq.Name) { strDrvName = pq.QueueDriver.Name; bSuccess = true; break; } } } catch { } return(bSuccess); }
private void init_combo_size() { //PaperSize pkSize; //for (int i = 0; i < printSettings.PaperSizes.Count; i++) //{ // pkSize = printSettings.PaperSizes[i]; // this.selected_parper.Items.Add(pkSize); //} PrintServer myPS = new PrintServer(); PrintQueueCollection myPrintQueues = myPS.GetPrintQueues(); int check_print = 0; foreach (PrintQueue pq in myPrintQueues) { pq.Refresh(); string temp = ""; //check_print = this.SpotTroubleUsingProperties(ref temp, pq); //if (check_print == 0 && !pq.IsOffline) if (!pq.IsOffline) { this.checkedList_mayin.Items.Add(pq.FullName, false); } }// end for each print queue }
/// <summary> /// Start watching print events /// </summary> public void Start() { lock (accesslock) { if (!isRunning) { Task.Factory.StartNew(() => { isRunning = true; printers = new ArrayList(); printServer = new PrintServer(); foreach (var pq in printServer.GetPrintQueues()) { var pqm = new PrintQueueHook(pq.Name); pqm.OnJobStatusChange += pqm_OnJobStatusChange; pqm.Start(); printers.Add(pqm); } }, CancellationToken.None, TaskCreationOptions.None, factory.GetTaskScheduler()).Wait(); } } }
public void Refresh() { setSpoolerStatus(); string deFaultPrinter = GetDefaultPrinter(); Application.Current.Properties["dp"] = deFaultPrinter; defaultPrinter.Text = deFaultPrinter; defaultPrinter.Foreground = new SolidColorBrush(Colors.Green); string dp = Application.Current.Properties["dp"].ToString(); PrintServer myPrintServer = new PrintServer(dp); // List the print server's queues PrintQueueCollection myPrintQueues = myPrintServer.GetPrintQueues(); String printQueueNames = "My Print Queues:\n\n"; noj.Text = GetNumberOfPrintJobs(deFaultPrinter).ToString(); foreach (string printer in PrinterSettings.InstalledPrinters) { this.cboPrinter.Items.Add(printer.ToString()); PrinterSettings p = new PrinterSettings(); p.PrinterName = printer; if (p.IsDefaultPrinter) { cboPrinter.Text = printer.ToString(); } } }
/// <summary> Get the support printer list. </summary> /// <param name="listPrinters">Used to store the supported printers.</param> /// <returns> None. </returns> /// <remarks> If the port of printer isn't support, the printer will /// not store in the list. The printer in the list were sorted by /// name. The default printer will be the 1st element, if it is in the /// list. </remarks> public static void GetSupportPrinters(List <string> listPrinters) { listPrinters.Clear(); try { // If spooler was stopped, new PrintServer( null ) will throw // a exception. string strDefPrinter = ""; PrinterSettings settings = new PrinterSettings(); PrintServer myPrintServer = new PrintServer(null); PrintQueueCollection myPrintQueues = myPrintServer.GetPrintQueues(); foreach (PrintQueue pq in myPrintQueues) { PrintDriver queuedrv = pq.QueueDriver; if (IsSupportPrinter(queuedrv.Name) == true) { if (EnumPortType.PT_UNKNOWN != (EnumPortType)dll.CheckPortAPI(pq.Name)) { listPrinters.Add(pq.Name); } } settings.PrinterName = pq.Name; if (settings.IsDefaultPrinter) { strDefPrinter = pq.Name; } } } catch { } }
private void Form1_Load(object sender, EventArgs e) { checkedListBoxPrinters.Width = splitContainer1.Panel1.Width; checkedListBoxPrinters.Height = splitContainer1.Panel1.Height - checkedListBoxPrinters.Top; listBoxPrinters.Width = splitContainer1.Panel2.Width; listBoxPrinters.Height = splitContainer1.Panel2.Height - listBoxPrinters.Top; PrintServer ps = new PrintServer(); PrintQueueCollection pqs = ps.GetPrintQueues(); foreach (PrintQueue pq in pqs) { if (pq.IsXpsDevice) { listBoxPrinters.Items.Add(pq.Name + " (XPSデバイス)"); } else if (pq.QueuePrintProcessor.Name == "mariaprint") { int i = checkedListBoxPrinters.Items.Add(pq.Name); checkedListBoxPrinters.SetItemChecked(i, true); } /* * else if (pq.QueuePrintProcessor.Name != "winprint") * { * listBoxPrinters.Items.Add(pq.Name + " (独自プリントプロセッサ)"); * } */ else { checkedListBoxPrinters.Items.Add(pq.Name); } } }
/// <summary> /// Init the print server /// </summary> private void InitServer() { this.printServer = new PrintServer(); this.printServer.OnPrinterLoaded = this.OnPrinterLoaded; this.printServer.OnPrinterChanged = this.OnPrinterSelected; this.printServer.OnPrintModeChanged = this.OnPrintModeChanded; }
/// <summary> /// /// </summary> /// <param name="name"></param> /// <returns></returns> public static PrintQueue GetPrintQueue(string name, string host) { if (String.IsNullOrWhiteSpace(name)) { return(null); } try { dynamic printServer; PrintQueue printQueue = null; if (String.IsNullOrWhiteSpace(host) || host == Environment.MachineName) { printServer = new LocalPrintServer(); } else { printServer = new PrintServer(host); } if (printServer == null) { return(null); } //name = name.Replace(host, ""); LogHelper.LogDebug("SSSS"); printServer.Refresh(); LogHelper.LogDebug("Refresh"); PrintQueueCollection printerCollection = printServer.GetPrintQueues(); if (printerCollection == null) { return(null); } LogHelper.LogDebug("Queues " + printerCollection.Count()); foreach (PrintQueue printer in printerCollection) { printer.Refresh(); LogHelper.LogDebug("Name " + printer.Name); if (printer.Name == name) { LogHelper.LogDebug("Has queue"); printQueue = printer; } } LogHelper.LogDebug("Out "); return(printQueue); } catch (Exception ex) { LogHelper.Log(ex); return(null); } }
private void buttonShowJobs_Click(object sender, EventArgs e) { try { string psName = ""; PrintServer _ps = new PrintServer();//(@"\\" + psName); PrintQueueCollection _psAllQueues = _ps.GetPrintQueues(); StringBuilder prnStr = new StringBuilder(); foreach (PrintQueue pq in _psAllQueues) { try { pq.Refresh(); //_pq.IsProcessing(); PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); foreach (PrintSystemJobInfo job in jobs) { prnStr.Append("\r\n"); prnStr.Append(pq.Name); prnStr.Append(" : "); prnStr.Append(pq.Location); prnStr.Append("\r\n"); prnStr.Append(job.JobName); prnStr.Append(" ID: "); prnStr.Append(job.JobIdentifier); prnStr.Append(" ID: "); prnStr.Append(job.NumberOfPagesPrinted); prnStr.Append("/"); prnStr.Append(job.NumberOfPages); prnStr.Append(" st:"); prnStr.Append(job.JobStatus.ToString()); prnStr.Append("\r\n-------------------------------------\r\n"); } } catch (Exception ex) { string sEvent = pq.Name + " : " + ex.Message; } } string jobList = prnStr.ToString(); if (string.IsNullOrEmpty(jobList)) { this.textBox1.Text = "No job in queue."; } else { this.textBox1.Text = jobList; } } catch (System.Exception ex) { this.textBox1.Text = ex.Message; } }
public void SetList(PrintServer printServer) { this.printServer = printServer; foreach (var t in this.printServer.GetEngin().GetTemplates()) { this.listTemplates.Items.Add(t); } }
private static List <PrintQueue> GetAllPrinters() { var server = new PrintServer(); var printQueues = server.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }); List <PrintQueue> allVKP80 = printQueues?.Where(x => x.FullName.ToLower().Contains(PrinterName))?.ToList(); return(allVKP80); }
private bool checkPrintSuccess(string docName) { bool success = false; PrintServer myPrintServer = new PrintServer(); // List the print server's queues PrintQueueCollection myPrintQueues = myPrintServer.GetPrintQueues(); String printQueueNames = "My Print Queues:\n\n"; string printJob = "JOBS:\n\n"; foreach (PrintQueue pq in myPrintQueues) { printQueueNames += "\t" + pq.Name + "\n"; //HP LaserJet Pro MFP M127fw if (pq.Name == "HP LaserJet Pro MFP M127fw") { try { PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection(); if (jobs != null) { foreach (PrintSystemJobInfo job in jobs) { printJob += "\t" + job.Name + "\n"; if (job.Name == docName && (((job.JobStatus & PrintJobStatus.Completed) == PrintJobStatus.Completed) || ((job.JobStatus & PrintJobStatus.Printed) == PrintJobStatus.Printed))) { success = true; } else { success = false; } }// end for each print job } } catch (NullReferenceException e) { success = true; } break; } } Console.WriteLine(printQueueNames); MessageBox.Show(printJob); Console.WriteLine("\nPress Return to continue."); Console.ReadLine(); return(success); }
private void MainForm_Load(object sender, EventArgs e) { PrintServer ps = new PrintServer(); foreach (PrintQueue pq in ps.GetPrintQueues()) { cmbPrinters.Items.Add(pq.Name); } }
/// <summary> /// Writes <paramref name="documentPaginatorSource"/> to the printer. /// </summary> /// <param name="xpsPrinterDefinition"/> /// <param name="documentPaginatorSource"/> /// <param name="printTicketFactory"/> /// <exception cref="T:System.ArgumentNullException"><paramref name="xpsPrinterDefinition"/> is <see langword="null"/>.</exception> /// <exception cref="T:System.ArgumentNullException"><paramref name="documentPaginatorSource"/> is <see langword="null"/>.</exception> /// <exception cref="T:System.ArgumentNullException"><paramref name="printTicketFactory"/> is <see langword="null"/>.</exception> /// <exception cref="T:System.InvalidOperationException"/> /// <exception cref="T:System.Exception"/> public static void Print([NotNull] this IXpsPrinterDefinition xpsPrinterDefinition, [NotNull] IDocumentPaginatorSource documentPaginatorSource, [NotNull][InstantHandle] PrintTicketFactory printTicketFactory) { if (xpsPrinterDefinition == null) { throw new ArgumentNullException(nameof(xpsPrinterDefinition)); } if (documentPaginatorSource == null) { throw new ArgumentNullException(nameof(documentPaginatorSource)); } if (printTicketFactory == null) { throw new ArgumentNullException(nameof(printTicketFactory)); } using (var printServer = new PrintServer(xpsPrinterDefinition.Host)) { PrintQueue printQueue; try { printQueue = printServer.GetPrintQueue(xpsPrinterDefinition.Name); } catch (PrintQueueException printQueueException) { throw new InvalidOperationException($"Failed to get print queue '{xpsPrinterDefinition.Name}' on '{xpsPrinterDefinition.Host}'", printQueueException); } using (printQueue) { var xpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(printQueue); var printTicket = printTicketFactory.Invoke(printQueue); if (documentPaginatorSource is FixedDocumentSequence fixedDocumentSequence) { fixedDocumentSequence.PrintTicket = printTicket; xpsDocumentWriter.Write(fixedDocumentSequence, printTicket); } else if (documentPaginatorSource is FixedDocument fixedDocument) { fixedDocument.PrintTicket = printTicket; xpsDocumentWriter.Write(fixedDocument, printTicket); } else { xpsDocumentWriter.Write(documentPaginatorSource.DocumentPaginator, printTicket); } } } }
private static void DeletePrintedFiles( PrintServer printServer, string queueName, ConcurrentQueue <QueuedFile> files) { using (PrintQueue printerQueue = printServer.GetPrintQueue(queueName)) { DeletePrintedFiles(files, printerQueue); } }
/// <summary> /// Llena los combos con las impresoras instaladas en la computadora /// </summary> /// <history> /// [lchairez] 05/Feb/2016 Created /// </history> private void FillPrinters() { PrintServer server = new PrintServer(); foreach (PrintQueue queue in server.GetPrintQueues()) { cmbPrinterInvitation.Items.Add(queue.FullName); cmbPrinterMeal.Items.Add(queue.FullName); } }
public override void Start() { PrintServer PrintS = new PrintServer(); PrintQueue queue = new PrintQueue(PrintS, _window.PrintInformation.PrinterSettings.PrinterName); bool trouve; List <Document> tempDocToRemove; List <Document> tempDocInQueue; do { tempDocToRemove = new List <Document>(); tempDocInQueue = _window.DocumentsInQueue.ToList(); queue.Refresh(); foreach (Document theDoc in tempDocInQueue) { trouve = false; try { using (PrintJobInfoCollection jobinfo = queue.GetPrintJobInfoCollection()) { foreach (PrintSystemJobInfo job in jobinfo) { using (job) { if (job.Name.Contains(theDoc.Name)) { trouve = true; } } } } } catch (NullReferenceException) { } catch (RuntimeWrappedException) { } catch (InvalidOperationException) { } if (trouve == false) { tempDocToRemove.Add(theDoc); SetStatus(theDoc, State.Printed); } } foreach (Document theDoc in tempDocToRemove) { _window.DocumentsInQueue.Remove(theDoc); } } while (!_token.IsCancellationRequested || _stopWindow.Stopped); PrintS.Dispose(); queue.Dispose(); }
public void Init() { PrintServer ps = this.mServer.PrintSvr; for (int i = 0; i < ps.ListPrint.Count; i++) { PrintOneInfo poi = (PrintOneInfo)(ps.ListPrint[i]); //this.mNetPrintList.Add(poi); this.Printers.Add(poi); } }
/// <inheritdoc/> public virtual TXpsPrinterDefinition GetXpsPrinterDefinition(string fullName) { if (fullName == null) { throw new ArgumentNullException(nameof(fullName)); } PrintServer printServer; string name; if (Uri.TryCreate(fullName, UriKind.Absolute, out var uri)) { if (uri.IsUnc) { printServer = new PrintServer(@"\\" + uri.Host); name = Path.GetFileName(uri.LocalPath); } else { printServer = new LocalPrintServer(); name = fullName; } } else { printServer = new LocalPrintServer(); name = fullName; } TXpsPrinterDefinition result; using (printServer) { PrintQueue printQueue; try { printQueue = printServer.GetPrintQueue(name); } catch (PrintQueueException printQueueException) { throw new InvalidOperationException($"Failed to get print queue '{fullName}'", printQueueException); } using (printQueue) { result = this.XpsPrinterDefinitionFactory.Create(printQueue); } } return(result); }
private PrintQueue GetPrintQueue(string printerName) { using (var printServer = new PrintServer()) { // GetPrintQueue(queueName) might not work with some types of network printers, // but giving the queue description strangely works, but this is not a safe solution. // Instead we just get all queues and filter them, that always works. var queues = printServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }); return(queues.SingleOrDefault(pq => pq.FullName == printerName)); } }
private PrintQueueCollection listSharedPrinters() { PrintServer printServer = new PrintServer(); PrintQueueCollection printQueues = printServer.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }); return(printQueues); }
private static void CleanupPrintedFiles( IDictionary <string, ConcurrentQueue <QueuedFile> > printingQueues) { using (var printServer = new PrintServer()) { foreach (KeyValuePair <string, ConcurrentQueue <QueuedFile> > queue in printingQueues) { DeletePrintedFiles(printServer, queue.Key, queue.Value); } } }
public List <Printer> GetAllPrinters() { using (var printServer = new PrintServer()) { using (var printQueues = printServer.GetPrintQueues()) { return(printQueues.Select(p => new Printer { Name = p.FullName }).ToList()); } } }
private PrintQueue FindPrintQueueByName(string name) { PrintServer server = new PrintServer(); foreach (PrintQueue queue in server.GetPrintQueues(new EnumeratedPrintQueueTypes[] { EnumeratedPrintQueueTypes.Connections, EnumeratedPrintQueueTypes.Local })) { if (queue.Name == name) { return queue; } } return null; }
public Dictionary<string, int> GetAllPrinterQueues() { Dictionary<string, int> TempDict = new Dictionary<string, int>(); PrintServer myPrintServer = new PrintServer(); // Get all the printers installed on this PC // List the print server"s queues PrintQueueCollection myPrintQueues = myPrintServer.GetPrintQueues(); foreach (PrintQueue pq in myPrintQueues) { Application.DoEvents(); pq.Refresh(); if (pq.Name != null) { int PGcount = 0; try { if (pq.NumberOfJobs > 0) { // We know there are jobs. So we *have* to be able to get the collection at some point DateTime Bailout = DateTime.Now.AddSeconds(5); // Keep trying for 10 seconds or until I get a valid response string ErrMsg = "not yet retreived"; while (Bailout > DateTime.Now && ErrMsg != string.Empty) { try { PrintJobInfoCollection Jobs = pq.GetPrintJobInfoCollection(); Application.DoEvents(); foreach (PrintSystemJobInfo Job in Jobs) { PGcount += Job.NumberOfPages; ErrMsg = string.Empty; } } catch (Exception k) { ErrMsg = k.Message; MessageBox.Show(pq.Name, ErrMsg); } } } } catch { MessageBox.Show("Exception dork"); } TempDict.Add(pq.Name, PGcount); } } return TempDict; }
/// <summary> /// Initialize the print helper /// </summary> public PrintHelper() { PrinterSettings settings = new PrinterSettings(); foreach (PaperSize ps in settings.PaperSizes) { paperSizes.Add(ps); } using (PrintServer printServer = new PrintServer()) { Printers = printServer.GetPrintQueues().ToDictionary(p => p, p => new PrinterSettings() { PrinterName = p.FullName }); } }
private void Window_Loaded(object sender, RoutedEventArgs e) { var server = new PrintServer(); var queues = server.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections}); foreach (var queue in queues) { Console.WriteLine(queue.Name); var capabilities = queue.GetPrintCapabilities(); foreach (PageMediaSize size in capabilities.PageMediaSizeCapability) { Console.WriteLine(size.ToString()); } Console.WriteLine(); } }
public PrintQueueCollection GetPrinters() { try { if (!_cacheHelper.Contains("Printers")) { var printServer = new PrintServer(); _cacheHelper.Add("Printers", printServer.GetPrintQueues(new[] {EnumeratedPrintQueueTypes.Connections,EnumeratedPrintQueueTypes.Local})); } var printers = (PrintQueueCollection)_cacheHelper.GetData("Printers"); return printers; } catch (Exception ex) { ////TempFileLogger.LogException(ex); throw; } }
protected void Page_Load(object sender, EventArgs e) { if ( !IsPostBack ) { new Thread( new ThreadStart( metrics ) ).Start(); string client = System.Net.Dns.GetHostEntry( Request.ServerVariables["remote_addr"] ).HostName; litUser.Text = client; hlOEM.NavigateUrl = @"\\" + client + @"\C$\Windows\OEM"; hlBIOS.NavigateUrl = @"\\dr3docs1\Windows8\BIOS-Update"; hlFirmware.NavigateUrl = @"\\dr3docs1\Windows8\BIOS-Update\2-BIOS-Settings-OP7010-Basic.exe"; hlSoftware.NavigateUrl = @"\\iwmdocs\iwm\CIWMB-INFOTECH\Software2"; hlLync.NavigateUrl = @"\\iwmdocs\iwm\CIWMB-INFOTECH\HelpCenter\RKOEN\Website\OfficeShortcuts\Lync 2013.lnk"; hlWord.NavigateUrl = @"\\iwmdocs\iwm\CIWMB-INFOTECH\HelpCenter\RKOEN\Website\OfficeShortcuts\Word 2013.lnk"; hlOutlook.NavigateUrl = @"\\iwmdocs\iwm\CIWMB-INFOTECH\HelpCenter\RKOEN\Website\OfficeShortcuts\Outlook 2013.lnk"; } server = new PrintServer( @"\\DR3PRINT" ); printersCollection = server.GetPrintQueues(); foreach ( PrintQueue printer in printersCollection ) { if ( printer.Name.Contains( "HP" ) || printer.Name.Contains( "NPI9EA6A6" ) || printer.Name.Contains( "AUDITS" ) || printer.Name.Contains( "Cert" ) || printer.Name.Contains( "MICR" ) || printer.Name.Contains( "KEN-SCOTT" ) || printer.Name.Contains( "COASTAL" ) || printer.Name.Contains( "Tire" ) ) { continue; } printersOnServer.Add( printer.Name ); } floors = stripFloorNumbers( printersOnServer ); ddFloor.DataSource = floors; if ( !IsPostBack ) { ddFloor.DataBind(); ddFloor_SelectedIndexChanged( ddFloor, null ); } }
static void Main(string[] args) { Test1(); return; /*var window = new Window(); var viewer = new DocumentViewer(); viewer.Document = new XpsDocument(@"C:\Incoming\wordprocessor\art-of-war-ch1-4.xps", System.IO.FileAccess.Read).GetFixedDocumentSequence(); window.Content = viewer; window.Show(); var app = new Application(); app.Run(window); return;*/ DrawingContext context; GlyphTypeface glyphTypeface; face.TryGetGlyphTypeface(out glyphTypeface); for (int i = 32; i < 96; i++) { var s = String.Format("{0}", (char)i); var ft = ProduceFT(s); GlyphRun gr = null; var drawing = new DrawingGroup(); context = drawing.Open(); context.DrawText(ft, new Point(0, 0)); var walker = new GlyphRunWalker(); context.Close(); ObtainGlyphRuns(drawing, walker.GlyphRuns); walker.start(); Console.WriteLine("'{0}', {1}, {2}, {3}", s, ft.Width, ft.WidthIncludingTrailingWhitespace, glyphTypeface.AdvanceWidths[walker.current]); } Console.ReadLine(); var image = new BitmapImage(new Uri(@"file:///c:\incoming\pos\lrsc.png")); var server = new PrintServer(); var queue = new PrintQueue(server, "EPSON TM-T88V Receipt"); queue.UserPrintTicket = new PrintTicket() { PageMediaSize = new PageMediaSize(MmToPx(80), MmToPx(1)) }; var writer = PrintQueue.CreateXpsDocumentWriter(queue); writer.WritingPrintTicketRequired += (sender, e) => { Console.WriteLine("PrintTicketRequired"); }; var visual = new DrawingVisual(); context = visual.RenderOpen(); //var line1 = new FormattedText(" 1 2 3 4 5 6 7", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, face, size, Brushes.Black); //var line2 = new FormattedText("1234567890123456789012345678901234567890123456789012345678901234567890", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, face, size, Brushes.Black); //context.DrawImage(image, new Rect(ToPx(4), 0, ToPx(72), 68)); top += 68; DrawText(context, "Lone Ranges Shooting Complex"); DrawText(context, "107-109 Robinson Ave, BELMONT WA 6104"); DrawText(context, "Phone: (618) 9277 9200"); DrawText(context, "Dealer No.: 9993912"); DrawText(context, "ABN: 84 286 785 988"); DrawText(context, ""); DrawText(context, "7/03/2013 12:56 PM"); DrawText(context, ""); DrawText(context, "Name: DAVID CENTAMAN"); DrawText(context, "Member No.: 24453"); DrawText(context, "Served by: PAULD"); DrawText(context, ""); DrawText(context, "Own firearm - 'Peashooter' 20.00"); DrawText(context, "(1AKK469) [Safe 2-4]"); DrawText(context, "9mm Ammunition (60 rounds) 40.00"); DrawText(context, "Glock 19 9mm Magazine 10 rounds 55.95"); DrawText(context, "Nestea Lemon 3.50"); DrawText(context, "Nestea Lemon 3.50"); DrawText(context, "Snickers 53g 2.20"); DrawText(context, "Snickers 53g 2.20"); DrawText(context, ".44 Ruger Rifle (30 rounds) 100.00"); DrawText(context, ""); DrawText(context, " TOTAL 227.35"); DrawText(context, " GST 20.67"); DrawText(context, ""); DrawText(context, " Amount tendered 250.00"); DrawText(context, " Change 22.65"); context.Close(); writer.Write(visual); }
private PrintQueue GetPrintQueue() { if (_configuration == null) { return null; } // Connect to the print server PrintServer printServer = null; try { printServer = new PrintServer(_configuration.PrintServer); } catch (PrintServerException ex) { Logger.Instance.LogFormat(LogType.Error, this, "Invalid print server name! Make sure that the print server under '{0}' is running or correct the print server name (leave blank to use local computer's print server).", ex.ServerName); return null; } // Pick the desired printer (even if none is selected, for convenience) var enpqt = new[] { EnumeratedPrintQueueTypes.Connections, EnumeratedPrintQueueTypes.Local }; PrintQueue queue = printServer.GetPrintQueues(enpqt).FirstOrDefault(pq => pq.FullName.Equals(_configuration.PrinterName)); // If there was a printer found, return that one if (queue != null) { return queue; } // Otherwise see if we are supposed to return a custom named printer ... if (!string.IsNullOrWhiteSpace(_configuration.PrinterName)) { Logger.Instance.LogFormat(LogType.Warning, this, "Did not find a printer with name '{0}'. Using the default, local printer.", _configuration.PrinterName); } // Return the default, local printer (there is no default print queue for a print server other than the local server!). return LocalPrintServer.GetDefaultPrintQueue(); }
public void Print(string printerName, string content) { try { using (PrintServer ps = new PrintServer()) { using (PrintQueue pq = new PrintQueue(ps, printerName, PrintSystemDesiredAccess.AdministratePrinter)) { using (PrintQueueStream pqs = new PrintQueueStream(pq, Guid.NewGuid().ToString())) { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(pqs, Encoding.Unicode)) { writer.Write(content); writer.Flush(); } } } } } catch (Exception ex) { throw new Exception("Ошибка печати. " + ex.Message); } }
private PrintQueue GetPrintQueue(string printerName) { PrintServer server = null; if (printerName.StartsWith(@"\\", StringComparison.InvariantCulture)) { int indexOfSecondSlash = printerName.IndexOf('\\', 2); if (indexOfSecondSlash > 2) { string serverName = printerName.Substring(0, indexOfSecondSlash); printerName = printerName.Substring(indexOfSecondSlash + 1); server = new PrintServer(serverName); } } if (server == null) { server = new LocalPrintServer(); } return server.GetPrintQueue(printerName); }
protected void PollBtn_Click(object sender, EventArgs e) { List<String> problems = new List<String>(); PrintServer server = new PrintServer( @"\\DR3PRINT" ); PrinterObj printerobj; foreach ( PrintQueue printer in server.GetPrintQueues() ) { try { if ( printer.Name.Contains( "HP" ) || printer.Name.Contains( "NPI9EA6A6" ) || printer.Name.ToUpper().Contains( "PLOTTER" ) || printer.Name.Contains( "AUDITS" ) || printer.Name.Contains( "MICR" ) || printer.Name.Contains( "KEN-SCOTT" ) || printer.Name.Contains( "COASTAL" ) || printer.Name.Contains( "19-BW-MFP-01" ) || printer.Name.Contains( "17K-COLOR-03" ) ) { continue; } // For Debugging //if ( printer.Name.Equals( "17K-ColorMFP-04", StringComparison.OrdinalIgnoreCase ) ) //{ // ; //} printerobj = new PrinterObj( printer.Name ); if ( printerobj.Low ) { printerobj.sendLowReport(); } } catch ( Exception ex ) { problems.Add( printer.Name ); report( DateTime.Now.ToString() + printer.Name + " was not polled report. \n" + ex.ToString() ); } } if ( problems.Count > 0 ) { report( "" ); report( "================================" ); report( "Problem checking printers: " + DateTime.Now.ToString() ); foreach ( String printer in problems ) { report( printer ); } } report( "END REPORT - " + DateTime.Now.ToString() ); }
protected void LevelsBtn_Click(object sender, EventArgs e) { rblPrinters.Items.Clear(); PrintServer server = new PrintServer( @"\\DR3PRINT" ); foreach ( PrintQueue printer in server.GetPrintQueues() ) { // if sharp use different webpage if ( printer.Comment.Contains( "SHARP MX-4141N" ) ) { rblPrinters.Items.Add( new ListItem( printer.Name, "http://" + printer.Name + "/device_status.html" ) ); } else if ( printer.Name.Contains( "HP" ) || printer.Name.Contains( "NPI9EA6A6" ) || printer.Name.Contains( "PLOTTER" ) || printer.Name.Contains( "AUDITS" ) || printer.Name.Contains( "MICR" ) || printer.Name.Contains( "KEN-SCOTT" ) || printer.Name.Contains( "COASTAL" ) ) { continue; } else if ( printer.Name.Equals( "24-COLOR-01", StringComparison.OrdinalIgnoreCase ) || printer.Name.Equals( "17K-COLOR-03", StringComparison.OrdinalIgnoreCase ) ) { ListItem invalid = new ListItem( printer.Name, "https://" + printer.Name ); invalid.Enabled = false; invalid.Attributes.Add( "style", "color:#999" ); rblPrinters.Items.Add( invalid ); } else { rblPrinters.Items.Add( new ListItem( printer.Name, "https://" + printer.Name ) ); } } mpePrinters.Show(); mpeLevels.Hide(); }
static void Test1() { var page = new FixedPage(); var server = new PrintServer(); var queue = server .GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections }) //.Single(q => q.Name == "TOSHIBA e-STUDIO4520CSeriesPCL6"); .Single(q => q.Name == "novaPDF"); var writer = System.Printing.PrintQueue.CreateXpsDocumentWriter(queue); queue.CurrentJobSettings.Description = DateTime.Now.ToString(); var ticket = new PrintTicket() { PageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4) //PageOrientation = PageOrientation.ReverseLandscape }; writer.Write(new MyPaginator(), ticket); }
public void PrintReceipt(UserControl uc) { var dialog = new PrintDialog(); var printer = new PrintServer().GetPrintQueues() .FirstOrDefault(x => x.Name == _printerName); if (printer != null) dialog.PrintQueue = printer; uc.Measure(new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight)); uc.Arrange(new Rect(new Point(0, 0), uc.DesiredSize)); dialog.PrintVisual(uc, "receipt"); }