Beispiel #1
0
        private void OnPrintQueue_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var queue = _printServer.GetPrintQueue(PrintQueuesListBox.SelectedValue.ToString());

            QueueStatusTextBox.Text       = string.Format("Queue Status: {0}", queue.QueueStatus);
            JobStatusTextBlock.Text       = string.Empty;
            JobsListBox.DisplayMemberPath = "JobName";
            JobsListBox.SelectedValuePath = "JobIdentifier";
            JobsListBox.ItemsSource       = queue.GetPrintJobInfoCollection();
        }
Beispiel #2
0
        private void lstQueues_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            PrintQueue queue = printServer.GetPrintQueue(lstQueues.SelectedValue.ToString());

            lblQueueStatus.Text       = "Queue Status: " + queue.QueueStatus.ToString();
            lblJobStatus.Text         = "";
            lstJobs.DisplayMemberPath = "JobName";
            lstJobs.SelectedValuePath = "JobIdentifier";

            lstJobs.ItemsSource = queue.GetPrintJobInfoCollection();
        }
Beispiel #3
0
        private void WaitForPrinterToComplete(string inFile)
        {
            var filename = new FileInfo(inFile).Name;

            using (var printServer = new PrintServer())
            {
                var queue = printServer.GetPrintQueue(this.pdfPrinterName);
                while (true)
                {
                    queue.Refresh();

                    /// checking whether our file is still in queue
                    if (
                        0 == queue
                        .GetPrintJobInfoCollection()
                        .Count(job => job.Name.Contains(filename))
                        )
                    {
                        break;
                    }

                    Thread.Sleep(100);
                }
            }
        }
Beispiel #4
0
        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)
            {
            }
        }
Beispiel #5
0
        //public void Print()
        //{
        //    PrintDialog printDialog = new PrintDialog();
        //    LocalPrintServer printServer = new LocalPrintServer();
        //    PrintQueue pq = printServer.GetPrintQueue(PrinterVariables.PRINTERNAME);
        //    printDialog.PrintQueue = pq;
        //    FlowDocument flowDoc = new FlowDocument(new Paragraph(new Run(receipt)));
        //    flowDoc.Name = "Receipt";
        //    flowDoc.FontFamily =  new System.Windows.Media.FontFamily(PrinterVariables.FONTNAME);
        //    flowDoc.FontSize = PrinterVariables.FONTSIZE;

        //    IDocumentPaginatorSource idpSource = flowDoc;
        //    printDialog.PrintDocument(idpSource.DocumentPaginator, "Printing Receipt");

        //}

        public void PrintSilently()
        {
            PrintDialog printDialog = new PrintDialog();
            PrintQueue  pq;
            IDocumentPaginatorSource idpSource = flowDoc;

            try
            {
                if (Settings.Default.useNetworkPrinter)
                {
                    string printServerName = @"\\Coregaming";
                    string printQueueName  = "POS";

                    PrintServer ps = new PrintServer(printServerName);
                    pq = ps.GetPrintQueue(printQueueName);
                    flowDoc.PageWidth = printDialog.PrintableAreaWidth;
                }
                else
                {
                    LocalPrintServer printServer = new LocalPrintServer();
                    pq = printServer.GetPrintQueue(PrinterVariables.PRINTERNAME);
                }
                idpSource = flowDoc;
                printDialog.PrintQueue = pq;
                printDialog.PrintDocument(idpSource.DocumentPaginator, "Printing Receipt");
            }
            catch (Exception e)
            {
                MessageBox.Show("Error in PrintSilently():\n" + e.Message + "\n" + e.Data.ToString());
            }
        }
Beispiel #6
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var vis = new DrawingVisual();
            var dc  = vis.RenderOpen();

            dc.DrawImage(_image, new Rect {
                Width = _image.Width, Height = _image.Height
            });
            dc.Close();

            if (!Settings.TestMode)
            {
                var dlg     = new PrintDialog();
                var serv    = new PrintServer();
                var printer = serv.GetPrintQueue(Settings.PrinterName);
                dlg.PrintQueue = printer;
                //dlg.PrintTicket.CopyCount = 1;
                dlg.PrintTicket.PageOrientation = PageOrientation.Portrait;
                dlg.PrintTicket.PageResolution  = new PageResolution(300, 300);
                //PageMediaSize pageSize = new PageMediaSize(PageMediaSizeName.);
                dlg.PrintTicket.PageMediaSize = new PageMediaSize(PageMediaSizeName.NorthAmerica4x6);
                dlg.PrintVisual(vis, "Photobooth Free");
            }
            CountDownTimer          = new System.Timers.Timer();
            CountDownTimer.Interval = 8000;
            CountDownTimer.Enabled  = true;
            CountDownTimer.Elapsed += CountDownTimer_Elapsed;
        }
        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, "");
            //}
        }
Beispiel #8
0
        /// <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);
                    }
                }
            }
        }
Beispiel #9
0
 private static void DeletePrintedFiles(
     PrintServer printServer,
     string queueName,
     ConcurrentQueue <QueuedFile> files)
 {
     using (PrintQueue printerQueue = printServer.GetPrintQueue(queueName))
     {
         DeletePrintedFiles(files, printerQueue);
     }
 }
Beispiel #10
0
        /// <summary>
        /// 得到打印机里的打印job
        /// </summary>
        /// <param name="printerName"></param>
        public void GetJobs(string printerName)
        {
            //if (App.psta == null)
            //{
            //    App.psta = new Models.PageSta();
            //}

            PrintServer ps    = new PrintServer();
            PrintQueue  queue = ps.GetPrintQueue(printerName);

            App.psta.nowCount = queue.NumberOfJobs;
            ps.Dispose();
            queue.Dispose();
        }
Beispiel #11
0
        //[Drukowanie] Osługa zdarzenia kliknięcia Button Drukuj.
        private void Drukuj_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog pd = new PrintDialog();
            PrintServer ps = new PrintServer();
            PrintQueue  pq = ps.GetPrintQueue(Drukarka.SelectedValue.ToString());

            pd.PrintQueue = pq;

            Faktura.LayoutTransform = new ScaleTransform(5, 5);

            int pageMargin = 3;

            System.Windows.Size pageSize = new System.Windows.Size(pd.PrintableAreaWidth - pageMargin * 2, pd.PrintableAreaHeight - pageMargin);
            Faktura.Measure(pageSize);
            Faktura.Arrange(new Rect(pageMargin, pageMargin, pageSize.Width, pageSize.Height));

            switch (KolorWydruku.SelectedIndex)
            {
            case 0:
                pd.PrintQueue.DefaultPrintTicket.OutputColor = OutputColor.Monochrome;
                break;

            case 1:
                pd.PrintQueue.DefaultPrintTicket.OutputColor = OutputColor.Grayscale;
                break;

            case 2:
                pd.PrintQueue.DefaultPrintTicket.OutputColor = OutputColor.Color;
                break;
            }
            int  temp;
            bool cos = int.TryParse(IloscKopii.Text, out temp);

            if (IloscKopii.Text != "" && cos == true && temp > 1)
            {
                pd.PrintQueue.DefaultPrintTicket.CopyCount = temp;
            }

            pd.PrintTicket = pd.PrintQueue.DefaultPrintTicket;
            //pd.ShowDialog();
            string nazwaWydruku;

            nazwaWydruku = "Faktura" + NumerPrzesylki.Text;
            pd.PrintVisual(Faktura, nazwaWydruku);
            Faktura.LayoutTransform = null;
        }
Beispiel #12
0
 static void prepare()
 {
     try
     {
         PrinterSettings settings = new PrinterSettings();
         _printServer = new PrintServer();
         _printQueue  = _printServer.GetPrintQueue(settings.PrinterName);
     }
     catch (Exception ex)
     {
         MessageBox.Show(
             ex.Message,
             Application.ProductName,
             MessageBoxButtons.OK,
             MessageBoxIcon.Error);
     }
 }
        /// <summary>
        /// 关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            PrintServer ps    = new PrintServer();
            PrintQueue  queue = ps.GetPrintQueue(ConfigurationManager.AppSettings["printer"]);

            if (queue.NumberOfJobs == 0)
            {
                ps.Dispose();
                queue.Dispose();
                closeThis();
            }
            else
            {
                ps.Dispose();
                queue.Dispose();
                MessageBox.Show("请耐心等待", "打印还未完成");
            }
        }
Beispiel #14
0
        /// <summary>
        /// 清理打印机队列中的JOb
        /// </summary>
        public void ClearJobs()
        {
            //清空打印机里残留的队列
            PrintServer ps    = new PrintServer();
            PrintQueue  queue = ps.GetPrintQueue(ConfigurationManager.AppSettings["printer"]);

            queue.Refresh();
            PrintJobInfoCollection allPrintJobs = queue.GetPrintJobInfoCollection();

            foreach (PrintSystemJobInfo printJob in allPrintJobs)
            {
                printJob.Cancel();
            }
            //释放资源
            ps.Dispose();
            queue.Dispose();
            allPrintJobs.Dispose();
        }
Beispiel #15
0
 /// <summary>
 /// setup printer
 /// </summary>
 /// <returns></returns>
 public PrintQueue SelectedPrintServer()
 {
     try
     {
         PrintServer printServer = null;
         printServer = new PrintServer();
         if (printServer == null)
         {
             return(null);                    //没有找到打印机服务器
         }
         PrinterSettings settings   = new PrinterSettings();
         var             printQueue = printServer.GetPrintQueue(settings.PrinterName);
         return(printQueue);
     }
     catch (Exception)
     {
         return(null);//没有找到打印机
     }
 }
Beispiel #16
0
        /// <summary>
        /// Start watching print events
        /// </summary>
        public static void Start(string printerName)
        {
            //if (!isRunning)
            {
                lock (accesslock)
                {
                    printers    = new ArrayList();
                    printServer = new PrintServer();

                    PrintQueue printQueue = printServer.GetPrintQueue(printerName);
                    var        pqHook     = new PrintQueueHook(printQueue.Name);
                    pqHook.OnJobStatusChange += pqm_OnJobStatusChange;
                    pqHook.Start();
                    printers.Add(pqHook);

                    isRunning = true;
                }
            }
        }
Beispiel #17
0
        public void load(string nomeStampante)
        {
            //http://stackoverflow.com/questions/1018001/is-there-a-net-way-to-enumerate-all-available-network-printers
            var match = Regex.Match(nomeStampante, @"(?<machine>\\\\.*?)\\(?<queue>.*)");

            if (match.Success)
            {
                _printQueue = new PrintServer(match.Groups["machine"].Value).GetPrintQueue(match.Groups["queue"].Value);
            }
            else
            {
                _printQueue = _printServer.GetPrintQueue(nomeStampante);
            }

            try {
                _printCapabilities = _printQueue.GetPrintCapabilities();
            } catch (Exception) {
                // Le stampanti shinko in rete non supportano questa operazione
            }

            _printDialog            = new PrintDialog();
            _printDialog.PrintQueue = _printQueue;
        }
Beispiel #18
0
        public static void PrintPDF(string filePath, string Printer = null)
        {
#if ( Print_Using_Adobe_Reader )
            // Define or otherwise determine the path of the Adobe reader
            PdfFilePrinter.AdobeReaderPath = @Properties.Settings.Default.AdobeReader;

            if (string.IsNullOrWhiteSpace(printerName))
            {
                // Present a Printer settings dialogue to the user so that they may select the printer
                // to use.
                PrinterSettings settings = new PrinterSettings();
                settings.Collate = false;

                PrintDialog printerDialog = new PrintDialog();
                printerDialog.AllowSomePages              = false;
                printerDialog.ShowHelp                    = false;
                printerDialog.PrinterSettings             = settings;
                printerDialog.AllowPrintToFile            = true;
                printerDialog.PrinterSettings.PrintToFile = true;

                DialogResult result = printerDialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    printerName = settings.PrinterName;
                }
                else
                {
                    return;
                }
            }

            // Print the document on the selected printer (We are ignoring all other print
            // options here

            PdfFilePrinter printer = new PdfFilePrinter(filePath, printerName);

            try
            {
                printer.Print();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
#else
            if (!File.Exists(filePath))
            {
                return;
            }
            // This is a massive bodge!
            ((App)App.Current).EventPage.Dispatcher.Invoke(delegate()
            {
                PdfDocumentView pdfViewer1 = new PdfDocumentView();


                pdfViewer1.Load(filePath);

                //if ( !string.IsNullOrWhiteSpace ( Printer ) )
                //    pdfViewer1.Print ( Printer );
                //else
                //    pdfViewer1.Print ( );

                PrintDialog print = new PrintDialog();

                if (!string.IsNullOrWhiteSpace(Printer))
                {
                    PrintQueue t = print.PrintQueue;
                    try
                    {
                        PrintServer server = new PrintServer();
                        print.PrintQueue   = server.GetPrintQueue(Printer);
                    }
                    catch (Exception)
                    {
                        System.Diagnostics.Debug.WriteLine("Failed to find printer");
                        print.PrintQueue = t;
                    }
                }

                //BitmapSource img = pdfViewer1.ExportAsImage ( 1 );


                print.PrintDocument(pdfViewer1.PrintDocument.DocumentPaginator, "Championship Solutions");
            });
#endif
        }
Beispiel #19
0
        /// <summary>
        /// 状态检测方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void stadtimer_Tick(object sender, EventArgs e)
        {
            System.Net.NetworkInformation.Ping        p       = new System.Net.NetworkInformation.Ping();
            System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();
            options.DontFragment = true;
            string data = "Test Data!";

            byte[] buffer  = Encoding.ASCII.GetBytes(data);
            int    timeout = 2000; // Timeout 时间,单位:毫秒

            //检查网络连接
            try
            {
                System.Net.NetworkInformation.PingReply reply = p.Send("baidu.com", timeout, buffer, options);
                if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
                {
                    stat.line          = true;
                    netLine.Text       = "网络已连接";
                    netLine.Foreground = Brushes.Green;
                }
                else
                {
                    stat.line          = false;
                    netLine.Text       = "网络连接已断开";
                    netLine.Foreground = Brushes.Red;
                }
            }
            catch
            {
                stat.line          = false;
                netLine.Text       = "网络异常,请联系管理员";
                netLine.Foreground = Brushes.Red;
            }

            if (stat.line == true)
            {
                //从网络获取机器状态
                HttpBLL httpbll = new HttpBLL();
                JSONBLL jsonbll = new JSONBLL();

                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("id", ConfigurationManager.AppSettings["id"]);

                string str = httpbll.GetResponseString(httpbll.CreatePostHttpResponse(ConfigurationManager.AppSettings["machine"], dic));

                if (str != null)
                {
                    JObject jo = JsonConvert.DeserializeObject <JObject>(str);

                    if (jo["code"].ToString() == "200")
                    {
                        JObject jo1;
                        string  str1 = jo["machine"].ToString();
                        if (str1 != null)
                        {
                            jsonbll.jsonToJobject(str1, out jo1);
                            stat.stat = jo1["nowStatus"].ToString();
                        }
                        else
                        {
                            stat.stat = "查无此机,若要正常使用,请检查配置文件与服务器";
                        }
                    }
                    else
                    {
                        stat.stat = "意外错误,未能与服务器正常通信";
                    }
                }
                else
                {
                    stat.stat = "意外错误,通信失败";
                }
            }
            else
            {
                stat.stat = "连接失败";
            }

            pageRemain.Text = App.set.remainPageNum.ToString();

            try
            {
                PrintServer ps    = new PrintServer();
                PrintQueue  queue = ps.GetPrintQueue(ConfigurationManager.AppSettings["printer"]);
                printerStaTxt.Text = queue.QueueStatus.ToString();
                ps.Dispose();
                queue.Dispose();
            }
            catch
            {
                printerStaTxt.Text = "打印服务未启动";
            }
        }
Beispiel #20
0
        public void outOfMemoryStampa()
        {
            long memoryPrima = Process.GetCurrentProcess().WorkingSet64;

            string[] nomiFilesImmagine = Costanti.NomiFileImmagini;

            // 10 foto x 50 giri = 500 foto
            foreach (string nomeFileImmagine in nomiFilesImmagine)
            {
                for (int giri = 1; giri <= 50; giri++)
                {
                    using (PrintServer ps1 = new PrintServer()) {
                        using (PrintQueue coda = ps1.GetPrintQueue(Costanti.NomeStampante)) {
                            PrintDialog dialog = new PrintDialog();
                            dialog.PrintQueue = coda;

                            Size areaStampabile = new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight);
                            // Ora creo il documento che andrò a stampare.
                            // L'uso di un FixedDocument, mi permetterà di interagire con misure, dimensioni e margini
                            FixedDocument document = new FixedDocument();
                            document.DocumentPaginator.PageSize = new Size(dialog.PrintableAreaWidth, dialog.PrintableAreaHeight);

                            // Creo una pagina della grandezza massima
                            FixedPage page1 = new FixedPage();
                            page1.Width               = document.DocumentPaginator.PageSize.Width;
                            page1.Height              = document.DocumentPaginator.PageSize.Height;
                            page1.VerticalAlignment   = VerticalAlignment.Center;
                            page1.HorizontalAlignment = HorizontalAlignment.Center;


                            // Per fare in modo che l'immagine venga centrata bene automaticamente, e non venga tagliata solo da una parte ma nel centro,
                            // non devo mettere le dimensioni al componente Image, ma devo creare
                            // una Grid più esterna con le dimensioni precise.
                            Grid grid = new Grid();
                            grid.Height = page1.Height;
                            grid.Width  = page1.Width;


                            // Creo una immagine che contiene la bitmap da stampare
                            Image image = new Image();
                            image.VerticalAlignment   = VerticalAlignment.Center;
                            image.HorizontalAlignment = HorizontalAlignment.Center;

                            // E' importante fare la dispose dell'oggetto Immagine
                            using (ImmagineWic qq = new ImmagineWic(nomeFileImmagine)) {
                                image.Source = qq.bitmapSource;

                                image.Stretch          = Stretch.UniformToFill;
                                image.StretchDirection = StretchDirection.Both;
                                grid.Children.Add(image);
                                page1.Children.Add(grid);


                                // add the page to the document
                                PageContent page1Content = new PageContent();
                                page1Content.Child = page1;
                                document.Pages.Add(page1Content);

                                //
                                // ----- STAMPA per davvero
                                //
                                dialog.PrintDocument(document.DocumentPaginator, "test" + giri.ToString());

                                foreach (var fixedPage in document.Pages.Select(pageContent => pageContent.Child))
                                {
                                    fixedPage.Children.Clear();
                                }
                            }

                            // ATTENZIONE: IMPORTANTE.
                            // Se non metto questa formula magica,
                            // il GC non pulisce la memoria occupata dalla bitmap (inspiegabilmente)
                            FormuleMagiche.rilasciaMemoria();
                        }
                    }

                    long memoryDopo = Process.GetCurrentProcess().WorkingSet64;
                    long consumata  = (memoryDopo - memoryPrima);

                    // Se supero il massimo impostato, probabilmente il gc non sta pulendo.
                    if (consumata > maxMem)
                    {
                        Assert.Fail("Probabilmente si sta consumando troppa memoria: diff(MB)=" + consumata / 1024);
                    }
                }
            }
        }
Beispiel #21
0
        public static async void mewPrintJobs_EventArrived(object sender, EventArrivedEventArgs e)
        {
            // Loading the setting file
            var settings = Properties.Settings.Default;

            settings.Reload();

            //Check if the program is enable
            Console.WriteLine("Checking if the program is enable");
            if (!settings.IsPageLimitEnable)
            {
                Console.WriteLine("Page Limit Disabled");
                return;
            }

            // Getting the print even infos
            Console.WriteLine("Getting the print even infos");
            ManagementBaseObject printJob = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
            string printerName            = printJob.Properties["Name"].Value.ToString().Split(',')[0];
            int    JobId = Convert.ToInt32(printJob.Properties["JobId"].Value);

            // Exclude the printers from the excluded printers list
            Console.WriteLine("Exclude the printers from the excluded printers list ");
            string[] PrinterList = settings.ExcludedPrinters.Split(';');
            foreach (string printer in PrinterList)
            {
                if (printer == printerName)
                {
                    Console.WriteLine("Printer Expluded");
                    return;
                }
            }


            PrintServer myPrintServer = new PrintServer();
            var         myPrintQueue  = myPrintServer.GetPrintQueue(printerName);
            var         job           = myPrintQueue.GetJob(JobId);

            job.Pause();

            // Waiting for the Spooling to end
            Console.WriteLine("Waiting for the Spooling to end...");
            while (job.IsSpooling)
            {
                job.Refresh();
            }
            Console.WriteLine("Spooling ended");

            Console.WriteLine("Stoping the Spooler Service");
            var StopSpoolerTask = ExecuteCmd.ExecuteCommandAsync("net stop spooler");

            int numberOfPages = job.NumberOfPages;


            Console.WriteLine("number of pages : " + numberOfPages);
            if (settings.PageLimit < numberOfPages)
            {
                MessageBox.Show("You can only print " + settings.PageLimit + " pages per day", "Prompt",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning,
                                MessageBoxDefaultButton.Button1,
                                MessageBoxOptions.DefaultDesktopOnly);
                ExecuteCmd.ExecuteCommandSync("net start spooler");
                job.Cancel();
                return;
            }


            PasswordPrompt form = new PasswordPrompt();

            form.ShowDialog();

            Console.WriteLine("Waiting for the spooler to stop to start it again...");
            AsyncPump.Run(async delegate
            {
                await StopSpoolerTask;
            });
            var StartSpoolerTask = ExecuteCmd.ExecuteCommandAsync("net start spooler");

            Task <PrintTrack> queryRequest = GetPrintTrack(form.StudentId);

            long sid;

            long.TryParse(form.StudentId, out sid);

            var password = Password(sid);

            if (form.Password == password)
            {
                Console.WriteLine("printing ...");
                PrintTrack printTrack = null;
                AsyncPump.Run(async delegate
                {
                    printTrack = await queryRequest;
                    await StartSpoolerTask;
                });
                if (printTrack != null)
                {
                    if (settings.PageLimit >= printTrack.PagesPrinted + numberOfPages)
                    {
                        job.Resume();
                        printTrack.PagesPrinted += numberOfPages;
                        db.SaveChanges();
                    }
                    else
                    {
                        job.Cancel();
                        MessageBox.Show("You can only print " + (settings.PageLimit - printTrack.PagesPrinted) + " pages more for today");
                    }
                }
                else
                {
                    if (settings.PageLimit >= numberOfPages)
                    {
                        job.Resume();
                        MessageBox.Show("number of pages : " + numberOfPages);
                        PrintTrack newPrintTrack = new PrintTrack
                        {
                            StudentId    = form.StudentId,
                            Password     = form.Password,
                            PagesPrinted = numberOfPages,
                            Date         = DateTime.Today,
                            ComputerName = System.Environment.MachineName
                        };
                        db.PrintTracks.Add(newPrintTrack);
                        db.SaveChanges();
                    }
                }
            }
            else
            {
                AsyncPump.Run(async delegate
                {
                    await StartSpoolerTask;
                });

                job.Cancel();
                MessageBox.Show("Invalid password!");
            }

            form.Dispose();

            Console.WriteLine("Done!");
        }
        /// <summary>
        /// 打印出错状态处理
        /// </summary>
        public void PrintWrong()
        {
            PrintServer ps    = new PrintServer();
            PrintQueue  queue = ps.GetPrintQueue(ConfigurationManager.AppSettings["printer"]);

            //int sendResult = 0;
            try
            {
                string proResult = "";
                getWrongMsg(ref proResult, queue);
                //messgeBoxBll msgBox = new messgeBoxBll();
                messgeBoxBll.Show("打印机出现问题,已经删除打印任务,本次操作不会计费", "问题排查:\n" + proResult);

                configbll.SaveConfig("printerStatus", "wrong");

                //if (queue.NumberOfJobs == 0 || wrongnum > 6)
                //{
                JObject jo;
                //上传结果
                string result = httpbll.updatePrintStatus("0");

                jsonbll.jsonToJobject(result, out jo);
                if (jo["code"].ToString() == "200")
                {
                    messgeBoxBll.Show("结果上传成功", jo["msg"].ToString());

                    //if (wrongnum > 6)
                    //{
                    //    messgeBoxBll.Show( "无法清理残余任务请联系管理员","问题排查:\n" + proResult);
                    //}

                    if (sameJobNum > 30)
                    {
                        messgeBoxBll.Show("超时", "打印机停留在同一任务时间过长");
                        proResult += "打印机停留在同一任务时间过长";
                    }
                    Log_m log = new Log_m("打印出错上传结果", "Y", "问题:" + proResult);
                    logbll.AddLog(log, ConfigurationManager.AppSettings["logFile"]);
                }
                else
                {
                    messgeBoxBll.Show("结果上传失败", jo["msg"].ToString());
                    //if (wrongnum > 6)
                    //{
                    //    messgeBoxBll.Show("无法清理残余任务请联系管理员", "问题排查:\n" + proResult);
                    //}
                    Log_m log = new Log_m("打印出错上传结果", "N", "问题:" + proResult + jo["msg"].ToString());
                    logbll.AddLog(log, ConfigurationManager.AppSettings["logFile"]);
                }

                //PrintBLL printbll = new PrintBLL();
                //printbll.ClearJobs();
                //}
                //else
                //{
                //  messgeBoxBll.Show("...........","正在还原初始状态");
                //}
            }
            catch (Exception ex)
            {
                messgeBoxBll.Show(ex.Message, "意外错误");
                Log_m log = new Log_m("打印出错上传结果", "N", "问题:" + ex.Message);
                logbll.AddLog(log, ConfigurationManager.AppSettings["logFile"]);

                //PrintBLL printbll = new PrintBLL();
                //printbll.ClearJobs();
            }
        }
Beispiel #23
0
        private void CboPrinters_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            try
            {
                LstDisplay.Items.Clear();
                PrintServer psrv;
                PrintQueue  pq;
                PrinterResolutionCollection prc;
                PaperSizeCollection         pszc;
                PaperSourceCollection       psc;
                PageSettings pgs;

                PrinterSettings ps = new PrinterSettings
                {
                    PrinterName = CboPrinters.SelectedItem.ToString()
                };

                prc  = ps.PrinterResolutions;
                psc  = ps.PaperSources;
                pszc = ps.PaperSizes;
                pgs  = ps.DefaultPageSettings;

                // display single value properties
                LstDisplay.Items.Add("Printer Name: " + ps.PrinterName);
                LstDisplay.Items.Add("Is Default Printer: " + ps.IsDefaultPrinter);
                LstDisplay.Items.Add("Print Range: " + ps.PrintRange);
                LstDisplay.Items.Add("PrintToFile: " + ps.PrintToFile);
                LstDisplay.Items.Add("Supports Color: " + ps.SupportsColor);
                LstDisplay.Items.Add("Duplex: " + ps.Duplex);
                LstDisplay.Items.Add("Can Duplex: " + ps.CanDuplex);
                LstDisplay.Items.Add("Collate: " + ps.Collate);
                LstDisplay.Items.Add("Copies: " + ps.Copies);
                LstDisplay.Items.Add("Maximum Copies: " + ps.MaximumCopies);
                LstDisplay.Items.Add("Minimum Page: " + ps.MinimumPage);
                LstDisplay.Items.Add("Maximum Page: " + ps.MaximumPage);
                LstDisplay.Items.Add("");

                // display setting collections
                LstDisplay.Items.Add("Printer Resolutions:");
                if (prc.Count > 0)
                {
                    foreach (object o in prc)
                    {
                        LstDisplay.Items.Add("   " + o);
                    }
                }
                else
                {
                    LstDisplay.Items.Add("   No Printer Resolutions.");
                }

                LstDisplay.Items.Add(string.Empty);
                LstDisplay.Items.Add("Paper Sources: ");
                if (psc.Count > 0)
                {
                    foreach (object o in psc)
                    {
                        LstDisplay.Items.Add("   " + o);
                    }
                }
                else
                {
                    LstDisplay.Items.Add("   No Paper Sources.");
                }

                LstDisplay.Items.Add(string.Empty);
                LstDisplay.Items.Add("Paper Sizes: ");
                if (pszc.Count > 0)
                {
                    foreach (object o in pszc)
                    {
                        LstDisplay.Items.Add("   " + o);
                    }
                }
                else
                {
                    LstDisplay.Items.Add("   No Paper Sizes.");
                }

                LstDisplay.Items.Add(string.Empty);
                LstDisplay.Items.Add("Default Page Settings: ");
                if (pgs.Landscape == true)
                {
                    LstDisplay.Items.Add("Orientation = Landscape");
                }
                else
                {
                    LstDisplay.Items.Add("Orientation = Portrait");
                }
                LstDisplay.Items.Add("Color = " + pgs.Color);
                LstDisplay.Items.Add("Printable Area = " + pgs.PrintableArea);
                LstDisplay.Items.Add("Margins = " + pgs.Margins);
                LstDisplay.Items.Add("Paper Source = " + pgs.PaperSource);
                LstDisplay.Items.Add("Page Bounds = " + pgs.Bounds);

                // display  print queues
                LstDisplay.Items.Add(string.Empty);
                LstDisplay.Items.Add("Print Queue:");

                // check if network printer and adjust print server
                if (CboPrinters.Text.StartsWith("\\\\"))
                {
                    string[] path;
                    path = CboPrinters.Text.Split('\\');
                    psrv = new PrintServer("\\\\" + path[2]);
                    pq   = psrv.GetPrintQueue(path[3]);
                }
                else
                {
                    psrv = new PrintServer();
                    pq   = psrv.GetPrintQueue(CboPrinters.Text);
                }

                int pjCount = 1;

                if (pq == null || pq.NumberOfJobs == 0)
                {
                    LstDisplay.Items.Add("   Empty");
                }
                else
                {
                    // loop the print job collection
                    foreach (PrintSystemJobInfo pjsi in pq.GetPrintJobInfoCollection())
                    {
                        LstDisplay.Items.Add(pjCount + ". Print Job Name: " + pjsi.Name);
                        LstDisplay.Items.Add("   Job Size: " + pjsi.JobSize);
                        LstDisplay.Items.Add("   Job Status: " + pjsi.JobStatus);
                        LstDisplay.Items.Add("   Position In PrintQueue: " + pjsi.PositionInPrintQueue);
                        LstDisplay.Items.Add("   Number of pages: " + pjsi.NumberOfPages);
                        LstDisplay.Items.Add("   Number of pages printed: " + pjsi.NumberOfPagesPrinted);
                        LstDisplay.Items.Add("   Submitter: " + pjsi.Submitter);
                        LstDisplay.Items.Add("   StartTimeOfDay: " + pjsi.StartTimeOfDay);
                        LstDisplay.Items.Add("   TimeJobSubmitted: " + pjsi.TimeJobSubmitted);
                        LstDisplay.Items.Add("   TimeSinceStartedPrinting: " + pjsi.TimeSinceStartedPrinting);
                        LstDisplay.Items.Add("   UntilTimeOfDay: " + pjsi.UntilTimeOfDay);
                        LstDisplay.Items.Add("   IsBlocked: " + pjsi.IsBlocked);
                        LstDisplay.Items.Add("   IsCompleted: " + pjsi.IsCompleted);
                        LstDisplay.Items.Add("   IsDeleted: " + pjsi.IsDeleted);
                        LstDisplay.Items.Add("   IsDeleting: " + pjsi.IsDeleting);
                        LstDisplay.Items.Add("   IsInError: " + pjsi.IsInError);
                        LstDisplay.Items.Add("   IsOffline: " + pjsi.IsOffline);
                        LstDisplay.Items.Add("   IsPaperOut: " + pjsi.IsPaperOut);
                        LstDisplay.Items.Add("   IsPaused: " + pjsi.IsPaused);
                        LstDisplay.Items.Add("   IsPrinted: " + pjsi.IsPrinted);
                        LstDisplay.Items.Add("   IsPrinting: " + pjsi.IsPrinting);
                        LstDisplay.Items.Add("   IsRestarted: " + pjsi.IsRestarted);
                        LstDisplay.Items.Add("   IsRetained: " + pjsi.IsRetained);
                        LstDisplay.Items.Add("   IsSpooling: " + pjsi.IsSpooling);
                        LstDisplay.Items.Add("   IsSpooling: " + pjsi.IsUserInterventionRequired);
                        pjCount++;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                LstDisplay.Items.Add("Error retrieving print settings");
            }
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            printersplit = args[0].TrimStart('z', 'p', 'r', 'i', 'n', 't', 'e', 'r', ':').Split('+');
            servername   = printersplit[0];
            sharename    = Uri.UnescapeDataString(printersplit[1]);
            printershare = "\\\\" + servername + "\\" + sharename;


            Ping ping = new Ping();

            try {
                pingReply = ping.Send(servername);
            } catch
            {
                MessageBox.Show("Print server is not available.\nPlease make sure you can access Zeon's network.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (pingReply.Status == IPStatus.Success)
            {
                PrintServer printServer = new PrintServer(@"\\" + servername);
                try
                {
                    PrintQueue printQueue = printServer.GetPrintQueue(printershare);
                } catch
                {
                    MessageBox.Show("Printer cannot be found on print server.\nPlease verify that printer exists.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                BackgroundWorker bg = new BackgroundWorker();
                bg.DoWork             += new DoWorkEventHandler(bg_DoWork);
                bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted);

                foreach (string printer in PrinterSettings.InstalledPrinters)
                {
                    if (printershare == printer)
                    {
                        printerExist = true;
                    }
                }
                if (printerExist)
                {
                    MessageBox.Show("Printer is already available on your computer.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    bg.RunWorkerAsync();
                    progressBar.ShowDialog();
                }
                void bg_DoWork(object sender, DoWorkEventArgs e)
                {
                    WshNetwork printerAdd = new WshNetwork();

                    printerAdd.AddWindowsPrinterConnection(printershare);
                }

                void bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
                {
                    do
                    {
                        foreach (string printer in PrinterSettings.InstalledPrinters)
                        {
                            if (printershare == printer)
                            {
                                printerExist = true;
                            }
                        }
                        Thread.Sleep(500);
                    } while (!printerExist);
                    progressBar.FormClosed += new FormClosedEventHandler(addComplete);
                    progressBar.Close();

                    void addComplete(object sender1, FormClosedEventArgs e1)
                    {
                        MessageBox.Show("Printer has been successfully added!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            else
            {
                MessageBox.Show("Print server is not available.\nPlease make sure you can access Zeon's network.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }