1

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

谢谢。

4

2 回答 2

1

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

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

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);
    }
于 2013-03-14T12:05:57.947 回答
0

您可以使用 FileSystemWatcher 类。

说明在这里

于 2013-03-14T13:12:28.737 回答