首页 > 解决方案 > 除非调用 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()调用似乎不起作用,因为文档没有放入打印机的池中。退出代码不表示错误。

如何在不显示消息框的情况下让程序工作?

我尝试过的,没有效果:


这不是应用程序退出太快的问题,因为我可以Thread.Sleep尽我所能(并在 Windows 任务管理器下确认)并且行为仍然是相同的。

标签: c#winforms.net-coreprinting

解决方案


推荐阅读