使用c# windows服务打印文件

本文关键字:打印 文件 服务 windows 使用 | 更新日期: 2023-09-27 18:03:47

我想使用windows服务器自动打印目录中的文件。只要将任何文件添加到目录中,它就会自动打印出来。我们如何才能做到这一点?

谢谢。

使用c# windows服务打印文件

我还没有测试过从另一个线程打印,但这两个选项之一应该工作。你可能需要修改代码才能使用。net 2,因为我只使用3.5 Sp1或4。

假设你有一个Print方法和一个Queue,其中itemtopprint是保存打印设置/信息的类

public Queue<ItemToPrint> PrintQueue = new Queue<ItemToPrint>();
    private BackgroundWorker bgwPrintWatcher;
    public void SetupBackgroundWorker()
    {
        bgwPrintWatcher = new BackgroundWorker();
        bgwPrintWatcher.WorkerSupportsCancellation = true;
        bgwPrintWatcher.ProgressChanged += new ProgressChangedEventHandler(bgwPrintWatcher_ProgressChanged);
        bgwPrintWatcher.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgwPrintWatcher_RunWorkerCompleted);
        bgwPrintWatcher.DoWork += new DoWorkEventHandler(bgwPrintWatcher_DoWork);
        bgwPrintWatcher.RunWorkerAsync();
    }
    void bgwPrintWatcher_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        while (!worker.CancellationPending)
        {
            // Prevent writing to queue while we are reading / editing it
            lock (PrintQueue)
            {
                if (PrintQueue.Count > 0)
                {
                    ItemToPrint item = PrintQueue.Dequeue();
                    // Two options here, you can either sent it back to the main thread to print
                    worker.ReportProgress(PrintQueue.Count + 1, item);
                    // or print from the background thread
                    Print(item);
                }
            }
        }
    }
    private void Print(ItemToPrint item)
    {
        // Print it here
    }
    private void AddItemToPrint(ItemToPrint item)
    {
        lock (PrintQueue)
        {
            PrintQueue.Enqueue(item);
        }
    }
    void bgwPrintWatcher_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        // Anything here will run from the main / original thread
        // PrintQueue will no longer be watched
    }
    void bgwPrintWatcher_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // Anything here will run from the main / original thread
        ItemToPrint item = e.UserState as ItemToPrint;
        // e.ProgressPercentage holds the int value passed as the first param
        Print(item);
    }

您可以使用FileSystemWatcher类。

描述这里