/// UpdateJobData
        #region UpdateJobData

        /// <summary>
        ///
        /// </summary>
        /// <param name="data"></param>
        /// <param name="printerName"></param>
        /// <param name="host"></param>
        /// <returns></returns>
        private static bool UpdateJobData(ref PrintJobData data, string printerName, string host)
        {
            bool updated = false;

            try
            {
                LogHelper.LogDebug("INNER START " + printerName);
                PrintQueue queue = GetPrintQueue(printerName, host);
                if (queue == null)
                {
                    return(false);
                }

                queue.Refresh();
                if (queue.NumberOfJobs > 0)
                {
                    bool quit = false;
                    while (!quit)
                    {
                        try
                        {
                            LogHelper.LogDebug("jobs " + queue.GetPrintJobInfoCollection().Count() + " | " + queue.NumberOfJobs);
                            foreach (PrintSystemJobInfo info in queue.GetPrintJobInfoCollection())
                            {
                                info.Refresh();
                                string docName       = info.Name;
                                int    NumberOfPages = info.NumberOfPages;
                                int    xxx           = info.NumberOfPagesPrinted;
                                LogHelper.LogDebug("Printing " + info.IsPrinting + " | Paused " + info.IsPaused + " | Spooling " + info.IsSpooling + " | IsDeleting " + info.IsDeleting);
                                LogHelper.LogDebug("pages " + NumberOfPages + " printed " + xxx);
                                if (data.PrintJobTitle.Document == docName && data.PrintJobTitle.TotalPages < xxx)
                                {
                                    data.PrintJobTitle.TotalPages = xxx;
                                    updated = true;
                                }
                            }

                            quit = true;
                        }
                        catch (Exception ex)
                        {
                            queue.Refresh();
                            LogHelper.LogDebug("refresh");
                            WPFNotifier.Error(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                WPFNotifier.Error(ex);
            }

            LogHelper.LogDebug("INNER END " + printerName);
            return(updated);
        }
Beispiel #2
0
        // получить статус задания
        public static string GetPrinterJobStatus(string prnName, string jobName)
        {
            string prnStatus = GetPrinterStatus(prnName);

            if (prnStatus == null)
            {
                return(null);
            }

            if (prnStatus.ToUpper() == "OK")
            {
                PrintQueue printer = GetPrintQueueByName(prnName);
                if (printer == null)
                {
                    return(null);
                }

                PrintSystemJobInfo job = printer.GetPrintJobInfoCollection().FirstOrDefault <PrintSystemJobInfo>(j => j.JobName == jobName);
                if (job == null)
                {
                    return(null);
                }
                else
                {
                    return(job.JobStatus.ToString());
                }
            }
            else
            {
                return(prnStatus);
            }
        }
Beispiel #3
0
        private static Status CancelJob(PrintQueue printQueue, string uniqueFileName)
        {
            // If you do not "refresh" the print queue, then getting information about the jobs will fail.
            printQueue.Refresh();
            PrintJobInfoCollection jobs = printQueue.GetPrintJobInfoCollection();

            // Extension is pulled out because some applications omit the file extension when it creates the job name.
            string             fileName = Path.GetFileNameWithoutExtension(uniqueFileName);
            PrintSystemJobInfo jobInfo  = jobs.FirstOrDefault(j => j.Name.Contains(fileName));

            jobInfo?.Cancel();

            //wait for 20 seconds to check if the job got deleted
            DateTime expireTime = DateTime.Now + TimeSpan.FromSeconds(20);

            while (jobInfo.IsDeleting && DateTime.Now < expireTime)
            {
                Thread.Sleep(100);
            }

            if (jobInfo.IsDeleted)
            {
                return(Status.Passed);
            }
            return(Status.Failed);
        }
        public static async Task JobStatus(PrintQueue queue, int timeout, int interval, Action <int> action)
        {
            using (queue)
            {
                int previousTotal = 0, total = 0, printed = 0, i = 0, count = timeout * 1000 / interval;

                while (true)
                {
                    queue.Refresh();
                    total = queue.GetPrintJobInfoCollection().Count();
                    if (i++ > count)
                    {
                        return;
                    }
                    if (previousTotal != total)
                    {
                        i = 0;
                        if (total < previousTotal)
                        {
                            printed += previousTotal - total;
                            action(printed);
                        }
                        previousTotal = total;
                    }
                    await Task.Delay(interval);
                }
            }
        }
Beispiel #5
0
        //private PrinterStatus _lastStatus;
        public PrinterStatus GetPrinterStatus()
        {
            PrinterStatus status = PrinterStatus.Ok;
            var           queue  = _printQueue.GetPrintJobInfoCollection();
            var           count  = queue.Count();

            //MessageBox.Show($"Count={count}   NumberOfJobs={_printQueue.NumberOfJobs}   QueueStatus= { _printQueue.QueueStatus}");//DEBUG
            if (count > 0)
            {
                status = PrinterStatus.QueueContainsElements;
            }
            else
            if (_printQueue.IsInError)
            {
                status = PrinterStatus.IsInError;
            }
            else
            if (_printQueue.IsOutOfPaper)
            {
                status = PrinterStatus.IsOutOfPaper;
            }
            else
            if (_printQueue.IsPaperJammed)
            {
                status = PrinterStatus.IsOutOfPaper;
            }
            else
            if (_printQueue.HasPaperProblem)
            {
                status = PrinterStatus.HasPaperProblem;
            }

            return(status);
        }
Beispiel #6
0
        private static void DeletePrintedFiles(
            ConcurrentQueue <QueuedFile> files,
            PrintQueue printerQueue)
        {
            var printingItems = new HashSet <string>(printerQueue
                                                     .GetPrintJobInfoCollection()
                                                     .Select(x => x.Name.ToUpper()));

            while (!files.IsEmpty)
            {
                files.TryPeek(out QueuedFile currentFile);
                if (printingItems.Contains(Path.GetFileName(currentFile.Path).ToUpper()))
                {
                    break;
                }

                files.TryDequeue(out QueuedFile dequeuedFile);
                try
                {
                    File.Delete(dequeuedFile.Path);
                    dequeuedFile.TaskCompletionSource.SetResult(dequeuedFile.Path);
                }
                catch { }
            }
        }
Beispiel #7
0
        public PrinterStatus GetPrinterStatus()
        {
            var queue = _printQueue?.GetPrintJobInfoCollection();
            var count = queue?.Count();

            if (count > 0)
            {
                return(PrinterStatus.QueueContainsElements);
            }

            if (_printQueue.IsInError)
            {
                return(PrinterStatus.IsInError);
            }

            if (_printQueue.IsOutOfPaper)
            {
                return(PrinterStatus.IsOutOfPaper);
            }

            if (_printQueue.IsPaperJammed)
            {
                return(PrinterStatus.IsOutOfPaper);
            }

            return(PrinterStatus.Ok);
        }
        public static async Task JobStatus2(PrintQueue queue, int timeout, int interval, Action <int, int> action, CancellationToken token = default)
        {
            using (queue)
            {
                int previousTotal = 0, total = 0, previousPrinted = 0, printed = 0, i = 0, count = timeout * 1000 / interval;
                PrintJobInfoCollection jobs;

                var exists = new HashSet <int>();
                while (!token.IsCancellationRequested)
                {
                    queue.Refresh();
                    jobs = queue.GetPrintJobInfoCollection();
                    foreach (var item in jobs)
                    {
                        if (exists.Contains(item.JobIdentifier))
                        {
                            continue;
                        }
                        exists.Add(item.JobIdentifier);
                    }
                    if (i++ > count)
                    {
                        return;
                    }
                    printed = (total = exists.Count) - jobs.Count();
                    if (previousPrinted != printed || previousTotal != total)
                    {
                        action(previousPrinted = printed, previousTotal = total);
                    }

                    await Task.Delay(interval);
                }
            }
        }
Beispiel #9
0
        private int Count_Jobs(string _ptr_device)
        {
            //IL_002b: Unknown result type (might be due to invalid IL or missing references)
            //IL_0031: Expected O, but got Unknown
            if (string.IsNullOrEmpty(_ptr_device))
            {
                return(0);
            }
            if (!Exist_Printer(_ptr_device))
            {
                MessageBox.Show("Printer '" + _ptr_device + "' is not present");
                return(0);
            }
            LocalPrintServer val        = (LocalPrintServer)(object)new LocalPrintServer();
            PrintQueue       printQueue = ((PrintServer)val).GetPrintQueue(_ptr_device);

            ((PrintSystemObject)printQueue).Refresh();
            int num = 0;

            if (printQueue.NumberOfJobs > 0)
            {
                PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection();
                {
                    foreach (PrintSystemJobInfo item in printJobInfoCollection)
                    {
                        _ = item;
                        num++;
                    }
                    return(num);
                }
            }
            return(num);
        }
Beispiel #10
0
        /// <summary>
        /// Gets the most recently submitted job
        /// </summary>
        /// <returns>The most recent job, or null if there are no jobs</returns>
        private PrintSystemJobInfo getLastJob()
        {
            DateTime           latestJobTime = DateTime.Now;
            PrintSystemJobInfo latestJob     = null;

            PrintQueue queue;

            foreach (string queueName in queueNamesToBlock)
            {
                queue = new PrintQueue(printServer, queueName);
                queue.Refresh();

                foreach (var job in queue.GetPrintJobInfoCollection())
                {
                    job.Refresh();

                    var time = job.TimeJobSubmitted;

                    if (time > latestJobTime)
                    {
                        latestJobTime = time;
                        latestJob     = job;
                    }
                }
            }

            return(latestJob);
        }
        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();
        }
Beispiel #12
0
        // получить список заданий принтера
        public static List <PrintSystemJobInfo> GetPrinterJobsList(string printerName)
        {
            PrintQueue printer = GetPrintQueueByName(printerName);

            if (printer == null)
            {
                return(null);
            }

            return(printer.GetPrintJobInfoCollection().ToList <PrintSystemJobInfo>());
        }
Beispiel #13
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 #14
0
        private void resumeAllJobs(PrintQueue queue)
        {
            queue.Refresh();

            foreach (var job in queue.GetPrintJobInfoCollection())
            {
                job.Refresh();
                job.Resume();
            }

            queue.Commit();
        }
Beispiel #15
0
        /// <summary>
        /// Cancel Print Job
        /// </summary>
        /// <param name="printName"></param>
        public static void ClearJob(string printName)
        {
            PrintServer localPrintServer = new LocalPrintServer();
            PrintQueue  pq = localPrintServer.GetPrintQueue(printName);

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

            foreach (PrintSystemJobInfo printJob in allPrintJobs)
            {
                printJob.Cancel();
            }
        }
Beispiel #16
0
        /// <summary>
        /// Pauses all of the current user's jobs in the queue, provided printing is disabled
        /// </summary>
        /// <param name="queue"></param>
        private void pauseAllJobs(PrintQueue queue)
        {
            queue.Refresh();

            foreach (PrintSystemJobInfo job in queue.GetPrintJobInfoCollection())
            {
                job.Refresh();

                logJob(job.JobIdentifier, job.NumberOfPages, job.TimeJobSubmitted, job.Submitter);
                pauseJob(job);
            }

            queue.Commit();
        }
Beispiel #17
0
        private int Wait_Ticket_Poll(string _ptr_device)
        {
            LocalPrintServer       localPrintServer       = new LocalPrintServer();
            PrintQueue             printQueue             = localPrintServer.GetPrintQueue(_ptr_device);
            PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection();

            if (printQueue.NumberOfJobs > 0)
            {
                if (printQueue.IsPrinting)
                {
                    return(2);
                }
                return(1);
            }
            return(0);
        }
Beispiel #18
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 #19
0
        public void Start()
        {
            OpenPrinter(_spoolerName, out _printerHandle, 0);
            if (_printerHandle != IntPtr.Zero)
            {
                //We got a valid Printer handle.  Let us register for change notification....
                _changeHandle = FindFirstPrinterChangeNotification(_printerHandle, (int)PRINTER_CHANGES.PRINTER_CHANGE_JOB, 0, _notifyOptions);
                // We have successfully registered for change notification.  Let us capture the handle...
                _mrEvent.Handle = _changeHandle;
                //Now, let us wait for change notification from the printer queue....
                _waitHandle = ThreadPool.RegisterWaitForSingleObject(_mrEvent, new WaitOrTimerCallback(PrinterNotifyWaitCallback), _mrEvent, -1, true);
            }

            _spooler = new PrintQueue(new PrintServer(), _spoolerName);
            foreach (PrintSystemJobInfo psi in _spooler.GetPrintJobInfoCollection())
            {
                objJobDict[psi.JobIdentifier] = psi.Name;
            }
        }
Beispiel #20
0
        public bool Printer_Poll(string _ptr_device)
        {
            if (string.IsNullOrEmpty(_ptr_device))
            {
                return(false);
            }
            LocalPrintServer       localPrintServer       = new LocalPrintServer();
            PrintQueue             printQueue             = localPrintServer.GetPrintQueue(_ptr_device);
            PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection();

            if (printQueue.NumberOfJobs > 0)
            {
                if (printQueue.IsPrinting)
                {
                    return(true);
                }
                return(false);
            }
            return(false);
        }
Beispiel #21
0
        /// <summary>
        /// The main method used to poll the print queue
        /// </summary>
        private void Poll()
        {
            PrintQueue spooler = new PrintQueue(new PrintServer(), printerName);

            string lastJobReported = null;

            while (!cancelled)
            {
                List <PrintSystemJobInfo> jobs = spooler.GetPrintJobInfoCollection().ToList();
                if (jobs.Count > 0)
                {
                    if (jobs[0].Name != lastJobReported)
                    {
                        OnJobsChanged(new JobChangedEventArgs(jobs[0]));
                        lastJobReported = jobs[0].Name;
                    }
                }

                Thread.Sleep(SleepDuration);
            }
        }
        internal void Start()
        {
            OpenPrinter(SpoolerName, out _printerHandle, 0);

            if (_printerHandle != IntPtr.Zero)
            {
                _changeHandle = FindFirstPrinterChangeNotification(_printerHandle,
                                                                   (int)PRINTER_CHANGES.PRINTER_CHANGE_JOB, 0, _notifyOptions);

                _mrEvent.SafeWaitHandle = new SafeWaitHandle(_changeHandle, true);


                _waitHandle = ThreadPool.RegisterWaitForSingleObject(_mrEvent, PrinterNotifyWaitCallback, _mrEvent, -1,
                                                                     true);
            }

            _spooler = new PrintQueue(new PrintServer(), SpoolerName);
            foreach (var psi in _spooler.GetPrintJobInfoCollection())
            {
                _objJobDict[psi.JobIdentifier] = psi.Name;
            }
        }
Beispiel #23
0
        public string GetQueue()
        {
            string           jobList = "";
            LocalPrintServer ps      = new LocalPrintServer();

            // Get the default print queue
            PrintQueue pq = ps.DefaultPrintQueue;

            // foreach (PrintQueue pq in myPrintQueues)
            // {
            pq.Refresh();
            PrintJobInfoCollection jobs = pq.GetPrintJobInfoCollection();

            foreach (PrintSystemJobInfo job in jobs)
            {
                jobList = jobList + "\n\tQueue:" + pq.Name;
                jobList = jobList + "\n\tLocation:" + pq.Location;
                jobList = jobList + "\n\t\tJob: " + job.JobName + " ID: " + job.JobIdentifier;
            }// end for each print job
             // }// end for e
            return(jobList);
        }
Beispiel #24
0
        private bool Print_Reset(string _ptr_device)
        {
            if (string.IsNullOrEmpty(_ptr_device))
            {
                return(false);
            }
            if (!Exist_Printer(_ptr_device))
            {
                return(false);
            }
            LocalPrintServer localPrintServer = new LocalPrintServer();
            PrintQueue       printQueue       = localPrintServer.GetPrintQueue(_ptr_device);

            printQueue.Refresh();
            if (printQueue.NumberOfJobs > 0)
            {
                PrintJobInfoCollection printJobInfoCollection = printQueue.GetPrintJobInfoCollection();
                foreach (PrintSystemJobInfo item in printJobInfoCollection)
                {
                    item.Cancel();
                }
            }
            return(true);
        }
        private void Hodoo_SIP30C(DataTable dt, string BizCode, bool IsNewData)
        {
            DataTable mdt = dt.Copy();

            for (int i = 0; i < mdt.Rows.Count; i++)
            {
                #region 카드발급프린터 대기열 작업완료시까지 기다림

                using (LocalPrintServer localPrinterServer = new LocalPrintServer())
                {
                    PrintQueue printQueue = localPrinterServer.GetPrintQueue(PrintName);

                    if (printQueue.NumberOfJobs > 0)
                    {
                        MessageBox.Show("인쇄 대기인 문서가 있습니다.");
                        return;
                    }

                    localPrinterServer.Dispose();
                }

                #endregion

                rPrintData = null;
                rPrintData = mdt.Rows[i];

                //일반(사진)
                info.xpos  = Convert.ToInt32(rPrintData["X_POS"].ToString().Trim());
                info.ypos  = Convert.ToInt32(rPrintData["Y_POS"].ToString().Trim());
                info.xsize = Convert.ToInt32(rPrintData["X_SIZE"].ToString().Trim());
                info.ysize = Convert.ToInt32(rPrintData["Y_SIZE"].ToString().Trim());

                //일반(승산)-카드프린터 클래스 생성
                info.bizcode     = BizCode;
                info.membername  = rPrintData["MEMBER_NAME_KOR"].ToString().Trim();
                info.memberno    = rPrintData["MEMBER_NO"].ToString().Trim();
                info.memberphoto = rPrintData["PHOTO"] == DBNull.Value ? null : (Byte[])rPrintData["PHOTO"];
                info.cardissueno = rPrintData["CARD_ISSUE_NO"].ToString().Trim();

                //예외(승산)-카드프린터 클래스 생성
                if (info.bizcode == "23")
                {
                    info.commodity_accountcode = rPrintData["COMMODITY_ACCOUNT_CODE"].ToString().Trim();
                    info.gccode = rPrintData["GC_CODE"].ToString().Trim();

                    info.memberno = string.Format("{0}-{1}{2}", info.memberno.Trim().Substring(2, 6)
                                                  , info.memberno.Trim().Substring(8, 2)
                                                  , info.commodity_accountcode.Trim());
                    if (info.membername.Length == 3)
                    {
                        info.membername = String.Format("{0} {1} {2}", info.membername.Substring(0, 1), info.membername.Substring(1, 1), info.membername.Substring(2, 1));
                    }
                }

                //예외(대천)-카드프린터 클래스 생성
                if (info.bizcode == "22")
                {
                    info.registercode = rPrintData["REGISTER_CODE"].ToString().Trim();
                    info.printdate    = DateTime.Today.ToString("yyyy.MM.dd");

                    if (info.memberno.Length == 10)
                    {
                        info.memberno = String.Format("{0}-{1}-{2}-{3}", info.memberno.Substring(0, 2), info.memberno.Substring(2, 2), info.memberno.Substring(4, 4), info.memberno.Substring(8, 2));
                    }

                    //기명=N
                    if (info.membername.Length == 3 && info.registercode == "N")
                    {
                        info.membername = String.Format("{0} {1} {2}", info.membername.Substring(0, 1), info.membername.Substring(1, 1), info.membername.Substring(2, 1));
                    }
                    //무기명=U
                    else
                    {
                        string strmemberName = info.membername;

                        if (info.membername.Length > 11)
                        {
                            strmemberName = info.membername.Substring(0, 11);
                        }

                        info.printdate = info.printdate + (info.membername.Equals("") ? "" : " " + strmemberName);
                    }
                }

                //예외(엘도라도)-카드프린터 클래스 생성
                if (info.bizcode == "51")
                {
                    info.membername = rPrintData["MEMBER_NAME_ENG"].ToString().Trim();
                }

                //일반(대천) - 마그네틱엔코딩
                info.mstrack1 = "";
                info.mstrack2 = String.Format("{0}={1}", rPrintData["CARD_ISSUE_NO"].ToString().Trim(), rPrintData["MEMBER_NO"].ToString().Trim());
                info.mstrack3 = "";

                //예외(승산) - 마그네틱엔코딩

                /*설명 : 1.승산 임시회원카드 = track1=골프혜택, track2=회원번호(8), track3=""
                 *       2.승산 임시회원카드 = track1=회원번호(8)골프혜택, track2="", track3=""
                 *       승산 임시회원카드는 정식카드 사용전까지 사용하며,
                 *       정식 마그네틱 저장형식은 추후 협의후 결정(기본 = track2사용, 카드번호(10자리)=회원번호(10자리))
                 */
                if (info.bizcode == "23")
                {
                    info.mstrack1 = String.Format("{0}{1}", rPrintData["MEMBER_NO"].ToString().Trim().Substring(2, 8), rPrintData["GC_CODE"].ToString().Trim()); //rPrintData["GC_CODE"].ToString().Trim();
                    info.mstrack2 = "";                                                                                                                          //rPrintData["CARD_ISSUE_NO"].ToString().Trim();//"";//String.Format("{0}", rPrintData["MEMBER_NO"].ToString().Trim().Substring(2, 8));
                    info.mstrack3 = "";
                }

                if (!WriteMagnetic(IsNewData, info.mstrack1, info.mstrack2, info.mstrack3))
                {
                    return;
                }

                if (IsNewData)
                {
                    Drawprint(PrintName);
                }

                suSender sender = new suSender {
                    BizCode = BizCode, sucMode = IsNewData ? SucessMode.NewData : SucessMode.Magstripe
                };

                bool IsSucess = true;
                using (LocalPrintServer localPrinterServer1 = new LocalPrintServer())
                {
                    PrintQueue printQueue = localPrinterServer1.GetPrintQueue(PrintName);

                    int  startTick = Environment.TickCount;
                    bool isTimeOut = false;

                    while (printQueue.NumberOfJobs > 0 & !(isTimeOut))
                    {
                        printQueue.Refresh();

                        int currentTick = Environment.TickCount;

                        if (currentTick - startTick > 60000)
                        {
                            isTimeOut = true;
                        }

                        System.Threading.Thread.Sleep(10);
                        Application.DoEvents();
                    }

                    if (isTimeOut)
                    {
                        PrintJobInfoCollection jobs = printQueue.GetPrintJobInfoCollection();

                        foreach (PrintSystemJobInfo job in jobs)
                        {
                            job.Cancel();
                        }



                        int deleteStateTime = System.Environment.TickCount;

                        string strmsg = "제한시간초과 - 인쇄가 완료되지 못했습니다. ";


                        while ((System.Environment.TickCount - deleteStateTime) < 1000)
                        {
                            printQueue.Refresh();
                        }


                        if (printQueue.NumberOfJobs > 0)
                        {
                            strmsg += "\n\r인쇄문서가 대기 중 입니다 . \n\r\n\r취소 후 다시 시도 하세요!";
                        }

                        IsSucess = false;
                        RaiseErrorEvent(new Exception(strmsg));
                        return;
                    }

                    if (IsSucess)
                    {
                        RaiseDataSucessEvent(sender, rPrintData);
                    }
                }
            }
        }
        public void Start()
        {
            OpenPrinter(_spoolerName, out _printerHandle, 0);
            if (_printerHandle != IntPtr.Zero)
            {
                //We got a valid Printer handle.  Let us register for change notification....
                _changeHandle = FindFirstPrinterChangeNotification(_printerHandle, (int)PRINTER_CHANGES.PRINTER_CHANGE_JOB, 0, _notifyOptions);
                // We have successfully registered for change notification.  Let us capture the handle...
                _mrEvent.Handle = _changeHandle;
                //Now, let us wait for change notification from the printer queue....
                _waitHandle = ThreadPool.RegisterWaitForSingleObject(_mrEvent, new WaitOrTimerCallback(PrinterNotifyWaitCallback), _mrEvent, -1, true);
            }

            _spooler = new PrintQueue(new PrintServer(), _spoolerName);
            foreach (PrintSystemJobInfo psi in _spooler.GetPrintJobInfoCollection())
            {
                objJobDict[psi.JobIdentifier] = psi.Name;
            }
        }
        public override void Start()
        {
            _wait.Reset();
            _inQueue = false;
            PrintServer PrintS = new PrintServer();
            PrintQueue  queue  = new PrintQueue(PrintS, _window.PrintInformation.PrinterSettings.PrinterName);
            int         trial  = 0;

            do
            {
                trial++;
                queue.Refresh();
                if (trial >= 3000 && trial < 6000)
                {
                    RefreshList(_document);
                    _window.Dispatcher.Invoke(new Action(() => { _stopWindow.skipVisibility(System.Windows.Visibility.Visible); }));
                    SetStatus(_document, State.Searching);
                }
                else if (trial >= 6000)
                {
                    SetStatus(_document, State.StillSearching);
                }
                try
                {
                    if (queue.NumberOfJobs > 0)
                    {
                        using (PrintSystemJobInfo job = queue.GetPrintJobInfoCollection().Last())
                        {
                            if (job.Name.Contains(_document.Name))
                            {
                                _inQueue = true;
                                SetStatus(_document, State.InQueue);
                                log.Info(_document.Name + " has been queued");
                            }
                        }
                    }
                }
                catch (NullReferenceException)
                {
                }
                catch (RuntimeWrappedException)
                {
                }
                catch (InvalidOperationException)
                {
                }
            } while (!_inQueue && trial < 10000 && !_token.IsCancellationRequested && !_stopWindow.Skip);
            PrintS.Dispose();
            queue.Dispose();

            if (trial >= 10000)
            {
                SetStatus(_document, State.Error);
                log.Error(_document.Name + " has made an error");
                if (!_window.Configuration.AutoRetry)
                {
                    System.Media.SystemSounds.Beep.Play();
                    _window.Dispatcher.Invoke(new Action(() => {
                        _stopWindow.retryVisibility(System.Windows.Visibility.Visible);
                        _window.Activate();
                        _stopWindow.Activate();
                    }));
                    _stopWindow.Retry.Reset();
                    _stopWindow.Retry.WaitOne();
                }
            }
            if (_stopWindow.Skip)
            {
                SetStatus(_document, State.Skipped);
                log.Info(_document.Name + " has been skipped");
            }
        }