首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >在没有打印对话框的情况下在C#中从Windows服务打印html文档

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

Stack Overflow用户
提问于 2009-01-06 04:20:50
回答 3查看 18.7K关注 0票数 7

我正在使用windows服务,并且希望在该服务启动时打印.html页。我正在使用这个代码,它打印得很好。但是一个打印对话框出现了,没有这个打印对话框我怎么打印?

代码语言:javascript
运行
AI代码解释
复制
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

EN

回答 3

Stack Overflow用户

发布于 2010-09-12 22:14:43

这是圣杯。

利用StaTaskScheduler (取自并行扩展插件(release on Code Gallery))。

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

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

代码语言:javascript
运行
AI代码解释
复制
    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
{
    /// <summary>Provides a scheduler that uses STA threads.</summary>
    public sealed class StaTaskScheduler : TaskScheduler, IDisposable
    {
        /// <summary>Stores the queued tasks to be executed by our pool of STA threads.</summary>
        private BlockingCollection<Task> _tasks;
        /// <summary>The STA threads used by the scheduler.</summary>
        private readonly List<Thread> _threads;

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

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

            // 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());
        }

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

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

        /// <summary>Determines whether a Task may be inlined.</summary>
        /// <param name="task">The task to be executed.</param>
        /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued.</param>
        /// <returns>true if the task was successfully inlined; otherwise, false.</returns>
        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);
        }

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

        /// <summary>
        /// Cleans up the scheduler by indicating that no more tasks will be queued.
        /// This method blocks until all threads successfully shutdown.
        /// </summary>
        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;
            }
        }
    }
}
票数 14
EN

Stack Overflow用户

发布于 2010-10-20 04:56:16

要增加Vadim的限制,您可以在打印前使用以下命令设置默认打印机:

代码语言:javascript
运行
AI代码解释
复制
    static void SetAsDefaultPrinter(string printerDevice)
    {
        foreach (var printer in PrinterSettings.InstalledPrinters)
        {
            //verify that the printer exists here
        }
        var path = "win32_printer.DeviceId='" + printerDevice + "'";
        using (var printer = new ManagementObject(path))
        {
            printer.InvokeMethod("SetDefaultPrinter",
                                 null, null);
        }

        return;
    }

并略微更改了PrintHtml方法:

代码语言:javascript
运行
AI代码解释
复制
    public void PrintHtml(string htmlPath, string printerDevice)
    {
        if (!string.IsNullOrEmpty(printerDevice))
            SetAsDefaultPrinter(printerDevice);


        Task.Factory.StartNew(() => PrintOnStaThread(htmlPath), CancellationToken.None, TaskCreationOptions.None, _sta).Wait();
    }

现在,我不知道这在一个繁重的打印环境中如何公平,考虑到大量更改默认打印机可能会出现并发问题。但到目前为止,这是我想出的最好的解决这个限制的方法。

票数 1
EN

Stack Overflow用户

发布于 2009-01-06 04:58:05

在windows服务中,Microsoft web浏览器控件不工作。我曾经使用过该代码,它在windows应用程序中工作得很好,但是当我在windows服务中使用时,程序就卡在这一行了

axWebBrowser1.Navigate(@"C:\mydoc.html",ref empty,ref empty);

感谢你的回复,Anup Pal

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/416314

复制
相关文章
限制堆栈的堆栈排序
原文题目:Stack sorting with restricted stacks
Jarvis Cocker
2019/07/19
1.2K0
java 堆栈的声明_Java 堆栈[通俗易懂]
堆栈是一种线性数据结构,用于存储对象的集合。它基于先进先出(LIFO)。 Java集合框架提供了许多接口和类来存储对象的集合。其中之一是Stack类,它提供了不同的操作,例如推,弹出,搜索等。
全栈程序员站长
2022/09/08
1.7K0
java 堆栈的声明_Java 堆栈[通俗易懂]
堆栈的实现
进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
小雨的分享社区
2022/10/26
7370
Java 数组实现堆栈操作
class Stack { private int stck[] ; private int tos ; Stack(int size) { // 一个参数的构造参数 stck = new int[size] ; // 创建数组(创建堆栈) tos = -1 ; // 空堆栈标识 -1 } // 堆栈操作的特性:先进后出、后进先出 void push(int item) { // 入栈
Mirror王宇阳
2020/11/13
5860
堆栈的分布
High Addresses ---> .----------------------. | Environment | |----------------------| | | Functions and variable are declared | STACK
用户4645519
2020/09/08
7140
堆栈
堆栈(英语:stack)又称为栈或堆叠,是计算机科学中的一种抽象数据类型,只允许在有序的线性数据集合的一端(称为堆栈顶端,英语:top)进行加入数据(英语:push)和移除数据(英语:pop)的运算。因而按照后进先出(LIFO, Last In First Out)的原理运作。
王小明_HIT
2020/04/21
1.1K0
堆栈
Js中的堆栈
堆heap是动态分配的内存,大小不定也不会自动释放,栈stack为自动分配的内存空间,在代码执行过程中自动释放。
WindRunnerMax
2020/08/27
3.2K0
Go 堆栈的理解
堆:堆可以被看成是一棵树,如:堆排序。在队列中,调度程序反复提取队列中第一个作业并运行,因为实际情况中某些时间较短的任务将等待很长时间才能结束,或者某些不短小,但具有重要性的作业,同样应当具有优先权。堆即为解决此类问题设计的一种数据结构。
孤烟
2020/09/27
1.5K0
java堆栈的区别
栈:一般存放基本数据类型和对象的引用(常量对象/字符串也可能在常量池中) 堆:一般存放new("对象") new的对象
用户9131103
2023/07/17
1250
堆栈溢出排查
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home/d5000/eas/easDmSync/heapdump.hprof
全栈程序员站长
2022/11/15
1K0
堆栈溢出排查
Lua调用C++时打印堆栈信息
公司的手游项目,使用的是基于cocos2d-x绑lua的解决方案(参数quick-x的绑定),虽然使用了lua进行开发,更新很爽了,但是崩溃依然较为严重,从后台查看崩溃日志时,基本上只能靠“猜”来复现bug。更为郁闷的是很多时候并没有使用log输出,在崩溃日志里还无法查看大概在哪一步操作崩溃的…
meteoric
2018/11/20
2.9K0
NPN_InvalidateRect的堆栈
node.dll!content::WebSchedulerImpl::postTimerTask(const blink::WebTraceLocation & location, blink::WebThread::Task * task, __int64 delayMs) 行 64 C++ node.dll!blink::TimerBase::setNextFireTime(double now, double delay) 行 113 C++ node.dll!blink::TimerBase::start(double nextFireInterval, double repeatInterval, const blink::WebTraceLocation & caller) 行 67 C++ node.dll!content::WebPluginImpl::invalidateRect(_NPRect * rect) 行 958 C++ > node.dll!NPN_InvalidateRect(_NPP * instance, _NPRect * invalidRect) 行 127 C++
龙泉寺扫地僧
2019/02/20
4780
js堆栈溢出的问题
    js是最令程序员头疼的问题了,不是语法也不是使用头疼,而是调试头疼,虽然有很方便的各种各样的调试工具,但经管这样有时候一个疏忽的小问题,会导致各种各样的奇怪问题的出现,今天笔者的同事就出现了这样的问题,苦闷了整整一天才找到了真正的问题。     出现js堆栈溢出的问题一般的情况有两种:       1.检查自己的js代码看代码中有没有死循环。     2.代码中引用了jQuery-1.4.2.min.js这个js实现一些动态效果或者是辅助,这个版本的jQuery就存在这样的问题(同事就是遇到了这个问
磊哥
2018/04/26
1.8K0
内部异常堆栈跟踪的结尾_异常堆栈跟踪不可用
大家好,我是架构君,一个会写代码吟诗的架构师。今天说一说内部异常堆栈跟踪的结尾_异常堆栈跟踪不可用,希望能够帮助大家进步!!!
Java架构师必看
2022/09/12
2.6K0
堆栈操作合法性 C++
假设以S和X分别表示入栈和出栈操作。如果根据一个仅由S和X构成的序列,对一个空堆栈进行操作,相应操作均可行(如没有出现删除时栈空)且最后状态也是栈空,则称该序列是合法的堆栈操作序列。请编写程序,输入S和X序列,判断该序列是否合法。
叶茂林
2023/07/30
2230
SpringBoot详细打印启动时异常堆栈信息
SpringBoot在项目启动时如果遇到异常并不能友好的打印出具体的堆栈错误信息,我们只能查看到简单的错误消息,以致于并不能及时解决发生的问题,针对这个问题SpringBoot提供了故障分析仪的概念(failure-analyzer),内部根据不同类型的异常提供了一些实现,我们如果想自定义该怎么去做?
恒宇少年
2019/10/08
1.4K0
SpringBoot详细打印启动时异常堆栈信息
定位生产问题时,异常堆栈莫名丢了,何解?
今天分享的这个知识有点冷,相信很多 Java 程序员很少遇到,废话不多说,直接进入排查问题的真实讨论现场。
一猿小讲
2020/08/18
1.3K0
定位生产问题时,异常堆栈莫名丢了,何解?
JAVA 堆栈类(Stack)的使用
出处:https://www.cnblogs.com/JJCS/p/3480982.html
用户7886150
2021/04/27
2K0
51单片机 堆栈与堆栈指针[通俗易懂]
堆栈是一种执行“先入后出”算法的数据结构。是在内存中的一个存储区域,数据一个一个顺序地存入(也就是“压入—PUSH”)这个区域之中。
全栈程序员站长
2022/11/03
2.8K0
Python实现堆栈
堆栈是一个后进先出的数据结构,其工作方式就像一堆汽车排队进去一个死胡同里面,最先进去的一定是最后出来。
一墨编程学习
2018/11/21
9070

相似问题

Qt、GCC、SSE和堆栈对齐

28

什么是“堆栈对齐”?

33

带堆栈操作的GCC内嵌组件

30

gcc x86窗口堆栈对齐

215

堆栈对齐是如何工作的?

12
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档