windows 带有“Copy”参数的WebBrowser.Document.ExecCommand在C#窗口应用程序中不起作用

vmdwslir  于 2022-11-26  发布在  Windows
关注(0)|答案(2)|浏览(176)

我正在尝试在C# windows应用程序中将HTML文本转换为RTF格式。为此,

  • 我用C#创建了一个示例Windows应用程序。
  • 已使用Web浏览器控件
  • 将HTML文本加载到其中。
  • 先后使用“Select”和“Copy”参数调用Web浏览器文档的对象ExecCommand方法。
  • “选择”命令可选择文本,但“复制”命令不会将选定文本复制到剪贴板。

下面是我使用的代码:

//Load HTML text
 System.Windows.Forms.WebBrowser webBrowser = new System.Windows.Forms.WebBrowser();
 webBrowser.IsWebBrowserContextMenuEnabled = true;
 webBrowser.Navigate("about:blank");
 webBrowser.Document.Write(htmlText);//htmlText = Valid HTML text

 //Copy formatted text from web browser
 webBrowser.Document.ExecCommand("SelectAll", false, null);
 webBrowser.Document.ExecCommand("Copy", false, null); // NOT WORKING

 //Paste copied text from clipboard to Rich Text Box control
 using (System.Windows.Forms.RichTextBox objRichTextBox = new System.Windows.Forms.RichTextBox())
       {
           objRichTextBox.SelectAll();
           objRichTextBox.Paste();
           string rtfTrxt = objRichTextBox.Rtf;
       }

备注:

  • 我还将Main方法标记为STAThreadAttribute
  • 这在客户端系统(Windows Server 2019)上不起作用
  • 在我的系统上工作正常(Windows 7 32位)
  • 我的系统和客户端系统上的浏览器版本相同,即IE 11
  • 我们不想使用任何像SautinSoft这样的付费工具。
bzzcjhmw

bzzcjhmw1#

我也遇到了同样的问题。这对我有帮助:

webBrowser.DocumentText = value;
            while (webBrowser.DocumentText != value) Application.DoEvents();
            webBrowser.Document.ExecCommand("SelectAll", false, null);
            webBrowser.Document.ExecCommand("Copy", false, null);
            richTextBoxActually.Text = "";
            richTextBoxActually.Paste();

wb可能需要几次迭代才能绘制出可以复制的文本。

kcrjzv8t

kcrjzv8t2#

我在任务中使用了以下解决方案:

// The conversion process will be done completely in memory.
        string inpFile = @"..\..\..\example.html";
        string outFile = @"ResultStream.rtf";
        byte[] inpData = File.ReadAllBytes(inpFile);
        byte[] outData = null;

        using (MemoryStream msInp = new MemoryStream(inpData))
        {

            // Load a document.
            DocumentCore dc = DocumentCore.Load(msInp, new HtmlLoadOptions());

            // Save the document to RTF format.
            using (MemoryStream outMs = new MemoryStream())
            {
                dc.Save(outMs, new RtfSaveOptions() );
                outData = outMs.ToArray();                    
            }
            // Show the result for demonstration purposes.
            if (outData != null)
            {
                File.WriteAllBytes(outFile, outData);
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
            }

相关问题