【问题标题】:Error when printing file but not when printing web page打印文件时出错,但打印网页时没有
【发布时间】:2011-07-30 21:03:51
【问题描述】:

使用InternetExplorer 对象,我可以打印网页。但是当我尝试打印文件时,出现以下错误:

System.Runtime.InteropServices.COMException: 调用的对象已断开连接 来自其客户。

我做错了什么?

这是代码(感谢this answer):

public class Program
{
    static void main(string[] args)
    {
        // this works
        (new HTMLPrinter()).Print("www.google.com");

        // this brings up the file in a browser 
        // but then throws an exception when checking print status!
        (new HTMLPrinter()).Print("C:\Temp\test.html");  
    }
}

public class HTMLPrinter
{
    private bool documentLoaded;
    private bool documentPrinted;

    private void ie_DocumentComplete(object pDisp, ref object URL)
    {
        documentLoaded = true;
    }

    private void ie_PrintTemplateTeardown(object pDisp)
    {
        documentPrinted = true;
    }

    public void Print(string htmlFilename)
    {
        documentLoaded = false;
        documentPrinted = false;

        InternetExplorer ie = new InternetExplorerClass();
        ie.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(ie_DocumentComplete);
        ie.PrintTemplateTeardown += new DWebBrowserEvents2_PrintTemplateTeardownEventHandler(ie_PrintTemplateTeardown);

        object missing = Missing.Value;

        ie.Navigate(htmlFilename, ref missing, ref missing, ref missing, ref missing);

        // An exception is thrown at 
        // SHDocVw.InternetExplorerClass.QueryStatusWB
        // only when trying to print a file!
        // Exception details: System.Runtime.InteropServices.COMException:
        // The object invoked has disconnected from its client.
        while (!documentLoaded && ie.QueryStatusWB(OLECMDID.OLECMDID_PRINT) != OLECMDF.OLECMDF_ENABLED)
            Thread.Sleep(100);        

        ie.ExecWB(OLECMDID.OLECMDID_PRINT, OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, ref missing, ref missing);
        while (!documentPrinted)
            Thread.Sleep(100);

        ie.DocumentComplete -= ie_DocumentComplete;
        ie.PrintTemplateTeardown -= ie_PrintTemplateTeardown;
        ie.Quit();
    }
}

【问题讨论】:

  • 我将 google 网页保存到磁盘,并打印了那个。似乎它与我的 html 文件有关。

标签: c# internet-explorer com printing


【解决方案1】:

以管理员身份运行程序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多