c# - 除非调用 MessageBox.Show(),否则 WebBrowser 的打印方法在控制台应用程序中不起作用
问题描述
我有一个程序应该打印作为参数提供给系统中默认打印机的字符串。该字符串是 HTML 格式的。
作为开发解决方案的尝试,我想出了以下代码:
程序.cs
using System;
using System.Windows.Forms;
using System.Threading;
namespace Print2
{
class Program
{
private const bool DEBUG = false;
[STAThread]
static void Main(string[] args)
{
string html = args[0];
RunBrowserThread(html);
}
// Mostly based on code by Hans Passant <https://stackoverflow.com/users/17034/hans-passant>
// See: https://stackoverflow.com/a/4271581/3258851
// (CC BY-SA 2.5)
private static void RunBrowserThread(string html)
{
var t = new Thread(() => {
var wb = new WebBrowser();
wb.DocumentCompleted += Browser_DocumentCompleted;
wb.DocumentText = html;
Application.Run();
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
static void Browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var wb = sender as WebBrowser;
wb.Print();
if (DEBUG)
MessageBox.Show("Printed " + wb.DocumentText);
Application.ExitThread();
}
}
}
这是一个控制台应用程序(.NET Core 3.1),我根据这个手动编辑了.csproj文件,以便支持:System.Windows.Forms.WebBrowser
Print2.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<Version>1.0.0-beta10</Version>
<AssemblyVersion>1.0.0.10</AssemblyVersion>
<FileVersion>1.0.0.10</FileVersion>
</PropertyGroup>
</Project>
我面临的问题是:当DEBUG
常量设置为false
(因此,没有显示消息框)时,wb.Print()
调用似乎不起作用,因为文档没有放入打印机的池中。退出代码不表示错误。
如何在不显示消息框的情况下让程序工作?
我尝试过的,没有效果:
- 根据链接的答案
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
在.csproj中定义 - 呼叫
Thread.Sleep()
或t.Join()
呼叫后立即t.Start()
。
这不是应用程序退出太快的问题,因为我可以Thread.Sleep
尽我所能(并在 Windows 任务管理器下确认)并且行为仍然是相同的。
解决方案
推荐阅读
- laravel - Guzzle http post 请求不适用于 laravel
- python-3.x - 具有依赖注入器 Python 的快速 API 获取 strategy_service.test(Test(name, id)) AttributeError: 'Provide' object has no attribute 'test'
- computer-science - 可以将哪些其他逻辑门添加到集合 {XOR} 以形成全集?
- mongodb - 考虑 MongoDB 设置模型
- java - 一段时间内停止对rabbitmq的消息消费
- responsive-design - 在图像上显式设置高度和宽度似乎会使尺寸属性无效
- sql-server - SQL Server 2019 - 对于 XML 路径 - 非 ascii 字符编码
- azure - Terraform 数据源无法获取现有资源
- r - 在 for 循环中 R 舍入 difftime 的问题
- serverless-framework - 管理数据库及其迁移的无服务器方式