当前位置:  开发笔记 > 编程语言 > 正文

在没有打印对话框的情况下,在C#中从Windows服务打印html文档

如何解决《在没有打印对话框的情况下,在C#中从Windows服务打印html文档》经验,为你挑选了1个好方法。

我正在使用Windows服务,我想在服务启动时打印.html页面.我正在使用此代码并且打印效果很好.但是打印对话框来了,如何在没有打印对话框的情况下打印?

public void printdoc(string document)
{
    Process printjob = new Process();
    printjob.StartInfo.FileName = document;
    printjob.StartInfo.UseShellExecute = true;
    printjob.StartInfo.Verb = "print";
    printjob.StartInfo.CreateNoWindow = true;
    printjob.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

    printjob.Start();
}

有没有其他方法来打印它而不显示打印对话框.

在此先感谢,Anup Pal



1> Vadim Kantor..:

这是圣杯.

利用StaTaskScheduler(取自Parallel Extension Extras(在Code Gallery上发布)).

特点:等待打印完成,不显示打印设置,希望可靠.

限制:需要C#4.0,使用默认打印机,不允许更改打印模板

    TaskScheduler Sta = new StaTaskScheduler(1);
    public void PrintHtml(string htmlPath)
    {
        Task.Factory.StartNew(() => PrintOnStaThread(htmlPath), CancellationToken.None, TaskCreationOptions.None, Sta).Wait();
    }

    void PrintOnStaThread(string htmlPath)
    {
        const short PRINT_WAITFORCOMPLETION = 2;
        const int OLECMDID_PRINT = 6;
        const int OLECMDEXECOPT_DONTPROMPTUSER = 2;
        using(var browser = new WebBrowser())
        {
            browser.Navigate(htmlPath);
            while(browser.ReadyState != WebBrowserReadyState.Complete)
                Application.DoEvents();

            dynamic ie = browser.ActiveXInstance;
            ie.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER, PRINT_WAITFORCOMPLETION);
        }
    }

//--------------------------------------------------------------------------
// 
//  Copyright (c) Microsoft Corporation.  All rights reserved. 
// 
//  File: StaTaskScheduler.cs
//
//--------------------------------------------------------------------------

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;

namespace System.Threading.Tasks.Schedulers
{
    /// Provides a scheduler that uses STA threads.
    public sealed class StaTaskScheduler : TaskScheduler, IDisposable
    {
        /// Stores the queued tasks to be executed by our pool of STA threads.
        private BlockingCollection _tasks;
        /// The STA threads used by the scheduler.
        private readonly List _threads;

        /// Initializes a new instance of the StaTaskScheduler class with the specified concurrency level.
        /// The number of threads that should be created and used by this scheduler.
        public StaTaskScheduler(int numberOfThreads)
        {
            // Validate arguments
            if (numberOfThreads < 1) throw new ArgumentOutOfRangeException("concurrencyLevel");

            // Initialize the tasks collection
            _tasks = new BlockingCollection();

            // Create the threads to be used by this scheduler
            _threads = Enumerable.Range(0, numberOfThreads).Select(i =>
            {
                var thread = new Thread(() =>
                {
                    // Continually get the next task and try to execute it.
                    // This will continue until the scheduler is disposed and no more tasks remain.
                    foreach (var t in _tasks.GetConsumingEnumerable())
                    {
                        TryExecuteTask(t);
                    }
                });
                thread.IsBackground = true;
                thread.SetApartmentState(ApartmentState.STA);
                return thread;
            }).ToList();

            // Start all of the threads
            _threads.ForEach(t => t.Start());
        }

        /// Queues a Task to be executed by this scheduler.
        /// The task to be executed.
        protected override void QueueTask(Task task)
        {
            // Push it into the blocking collection of tasks
            _tasks.Add(task);
        }

        /// Provides a list of the scheduled tasks for the debugger to consume.
        /// An enumerable of all tasks currently scheduled.
        protected override IEnumerable GetScheduledTasks()
        {
            // Serialize the contents of the blocking collection of tasks for the debugger
            return _tasks.ToArray();
        }

        /// Determines whether a Task may be inlined.
        /// The task to be executed.
        /// Whether the task was previously queued.
        /// true if the task was successfully inlined; otherwise, false.
        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            // Try to inline if the current thread is STA
            return
                Thread.CurrentThread.GetApartmentState() == ApartmentState.STA &&
                TryExecuteTask(task);
        }

        /// Gets the maximum concurrency level supported by this scheduler.
        public override int MaximumConcurrencyLevel
        {
            get { return _threads.Count; }
        }

        /// 
        /// Cleans up the scheduler by indicating that no more tasks will be queued.
        /// This method blocks until all threads successfully shutdown.
        /// 
        public void Dispose()
        {
            if (_tasks != null)
            {
                // Indicate that no new tasks will be coming in
                _tasks.CompleteAdding();

                // Wait for all threads to finish processing tasks
                foreach (var thread in _threads) thread.Join();

                // Cleanup
                _tasks.Dispose();
                _tasks = null;
            }
        }
    }
}

推荐阅读
360691894_8a5c48
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有