C# Windows 窗体应用程序中的 HTML 编辑器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-07-31 17:18:26  来源:igfitidea点击:

HTML Editor in a Windows Forms Application

提问by John

We are looking for a WYSIWYG editor control for our windows application (vb.net or c#) so that users can design HTML emails (to send using the SMTP objects in the dot net framework) before sending.

我们正在为我们的 windows 应用程序(vb.net 或 c#)寻找 WYSIWYG 编辑器控件,以便用户可以在发送之前设计 HTML 电子邮件(使用 dot net 框架中的 SMTP 对象发送)。

Currently all the available editors we can find have one of the following issues:

目前,我们可以找到的所有可用编辑器都存在以下问题之一:

  1. They rely on mshtml.dll or the web browser control which as proven for us to be unreliable as the HTML code and the editor get out of sync under windows 2000 (IE6)

  2. They are web-based, not a windows form control

  3. They place styles in the head of the document (see note below)

  1. 它们依赖于 mshtml.dll 或 Web 浏览器控件,事实证明这些控件不可靠,因为 HTML 代码和编辑器在 Windows 2000 (IE6) 下不同步

  2. 它们是基于 Web 的,而不是 Windows 窗体控件

  3. 他们将样式放在文档的头部(见下面的注释)

Unfortunately, as this HTML email articledescries the only sure way of making HTML emails to work with styles is to use them inline which now seems to be unsupported in many editors.

不幸的是,正如这篇HTML 电子邮件文章所描述的,使 HTML 电子邮件与样式一起工作的唯一可靠方法是使用它们内联,而现在许多编辑器似乎不支持这种方法。

Does anyone have any experience in this or could suggest a solution?

有没有人有这方面的经验或可以提出解决方案?

回答by Yaakov Ellis

I also needed a WYSIWYG editor for a Windows Forms project that I was working on. I wrote about the items that I found here. Eventually, I ended up using something that I found on CodeProject: A Windows Forms based text editor with HTML output. This does violate (a) above in that it uses the WebBrowser control. However, I couldn't find anything good that didn't do this (if you don't use the WebBrowser in some way, then you basically have to write your own HTML parser and renderer in order to handle the "What-You-See" part of WYSIWYG). The good thing about this control is that the source is easily customizable, so you can take away and add formatting options as you need (and if you want the styles to all be in-line, you can do this as well).

我还需要一个 WYSIWYG 编辑器用于我正在处理的 Windows 窗体项目。我写了我在这里找到的项目。最终,我最终使用了我在 CodeProject 上找到的东西:带有 HTML 输出的基于 Windows 窗体的文本编辑器。这确实违反了上面的 (a),因为它使用了 WebBrowser 控件。但是,我找不到任何不这样做的好东西(如果您不以某种方式使用 WebBrowser,那么您基本上必须编写自己的 HTML 解析器和渲染器来处理“What-You-见”所见即所得的部分)。这个控件的好处是源代码很容易自定义,因此您可以根据需要删除和添加格式选项(如果您希望所有样式都内嵌,您也可以这样做)。

回答by J Wynia

I've been using this one, which goes a little lower than the WebBrowser, but still uses MSHTML, which does spit out some ugly HTML. For my purposes, I am doing a multi-tabbed editor with WYSIWYG and HTML edit mode (using ICSharp.TextEditor) with a Buffer class to update whenever tabs change. As part of that Buffer class, I actually run the HTML through HTML Tidyand a few scrub-n-replace bits to get valid XHTML.

我一直在使用这个,它比 WebBrowser 低一点,但仍然使用 MSHTML,它确实会吐出一些难看的 HTML。出于我的目的,我正在使用 WYSIWYG 和 HTML 编辑模式(使用ICSharp.TextEditor)进行多选项卡编辑器,并在选项卡更改时更新 Buffer 类。作为该 Buffer 类的一部分,我实际上是通过 HTML Tidy和一些 Scrub-n-replace 位来运行 HTML以获得有效的 XHTML。

I only offer that as a solution because I, too, failed to find one that wasn't derived from MSHTML in some way and eventually just went ahead with the above solution to keep moving forward.

我只提供它作为一种解决方案,因为我也未能找到以某种方式不是从 MSHTML 派生的解决方案,最终只是继续上述解决方案以继续前进。

回答by Anax

Instead of searching for an HTML editor, consider the option of a RichText editor (which can be much easier to create) and then convert the final text into a HTML document.

与其搜索 HTML 编辑器,不如考虑选择 RichText 编辑器(创建起来更容易),然后将最终文本转换为 HTML 文档。

Provided you are required to use a minimal set of features (bold / italics etc) both the creation of the RT editor and the conversion of the final document into HTML format shouldn't be hard.

如果您需要使用最少的一组功能(粗体/斜体等),那么 RT 编辑器的创建和最终文档到 HTML 格式的转换应该不难。

If, on the other hand, you need to use more features (such as tables), you need to study the Rich Text Formatand implement the features you need.

另一方面,如果您需要使用更多功能(例如表格),则需要研究富文本格式并实现您需要的功能。

Additional resources:

其他资源:

回答by ChrisW

There is this HTML Edit Control for .NET(disclosure: I wrote it).

.NET有这个HTML 编辑控件(披露:我写的)。

It doesn't rely on any web browser; it's a Windows form control; and, it can cope with the style=attribute.

它不依赖任何网络浏览器;它是一个 Windows 窗体控件;并且,它可以应对该style=属性。

It's not exactly what you want: because it's designed for WYSIWYM, the toolbar doesn't have buttons to edit inline styles (although its rendering engine will render inline styles), the toolbar lets you specify only block-level elements like <p>and <h1>and <ul>and <table>; but if you wanted to, you could ask me about adding functionality (as described in the Developing New Functionalitysection).

这不完全是您想要的:因为它是为所见即所得设计的,工具栏没有编辑内联样式的按钮(尽管它的渲染引擎会渲染内联样式),工具栏只允许您指定块级元素,如<p>and<h1><ul>and <table>;但如果你愿意,你可以问我关于添加功能的问题(如开发新功能部分所述)。

回答by VampireKode

It's my first contribution.

这是我的第一个贡献。

You can use a RichTextBox. The RTF format is more than enough to create emails.

您可以使用 RichTextBox。RTF 格式足以创建电子邮件。

I recently wrote about how to load and save to hard disk, the contents of a RichTextBox.

我最近写了一篇关于如何加载和保存到硬盘的 RichTextBox 的内容。

Allows Copy and Paste. It's simple to use and with few buttons you can create your own commands.

允许复制和粘贴。它使用简单,只需几个按钮,您就可以创建自己的命令。

With RichTextBox1 
??? .SelStart = 0 
????.SelLength = Len (. Text) 
????.SelColor = vbRed
End With

Example for loading and saving.

加载和保存示例。

http://danielcatala.wordpress.com/2014/01/30/como-cargar-y-guardar-archivos-richtext-con-wpf/

http://danielcatala.wordpress.com/2014/01/30/como-cargar-y-guardar-archivos-richtext-con-wpf/

Private Sub btnCarga(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click

    Dim archivoCarga As New StreamReader("prueba.rtf")
    With RichTextBox1
        .Selection.Select(.Document.ContentStart, RichTextBox1.Document.ContentEnd)
        .Selection.Load(archivoCarga.BaseStream, System.Windows.DataFormats.Rtf)
    End With
End Sub

Private Sub btnGuarda(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click

    Dim archivoSalida As New StreamWriter("prueba.rtf")
    Dim bs As Stream = archivoSalida.BaseStream

    With RichTextBox1
        .Selection.Select(RichTextBox1.Document.ContentStart,     RichTextBox1.Document.ContentEnd)
        .Selection.Save(bs, System.Windows.DataFormats.Rtf)
    End With
End Sub

回答by Reza Aghaei

The simplest HTML editor in Windows Forms could be showing a <div contenteditable="true"></div>in a WebBrowsercontrol. It has built in support for common html text editing features like:

Windows 窗体中最简单的 HTML 编辑器可以<div contenteditable="true"></div>WebBrowser控件中显示一个。它内置了对常见 html 文本编辑功能的支持,例如:

  • Ctrl+Bto make the selection bold
  • Ctrl+Ito make the selection italic
  • Ctrl+Uto make the selection underlined
  • Ctrl+Ato select all text
  • Ctrl+Cto copy selection
  • Ctrl+Xto cut selection
  • Ctrl+Vto paste the selection
  • Ctrl+Kto insert a link
  • Ctrl+B使选择加粗
  • Ctrl+I使选择斜体
  • Ctrl+U使选择带有下划线
  • Ctrl+A选择所有文本
  • Ctrl+C复制选择
  • Ctrl+X剪切选择
  • Ctrl+V粘贴选择
  • Ctrl+K插入链接

However for a better user experience you can rely on DOM documentobject in WebBrowerand use its execCommandmethod and easily run commands like Bold, Italic, Underline, InsertOrderedList, InsertUnorderedList, InsertImage, FormatBlock, ForeColor, BackColor, and etc.

但是,为了获得更好的用户体验,您可以依赖 DOMdocument对象WebBrower并使用其execCommand方法并轻松运行诸如BoldItalicUnderlineInsertOrderedListInsertUnorderedListInsertImageFormatBlockForeColorBackColor等命令。

For example the following command inserts ordered list:

例如以下命令插入有序列表:

webBrowser1.Document.ExecCommand("InsertOrderedList", false, null);

Examlpe - Windows Forms HTML Editor

示例 - Windows 窗体 HTML 编辑器

Here I will share an example for a C# application and will show you easily you can implement an HTML editor.

在这里,我将分享一个 C# 应用程序示例,并向您展示如何轻松实现 HTML 编辑器。

enter image description here

在此处输入图片说明

public class HtmlEditor
{
    WebBrowser webBrowser;
    private dynamic doc;
    private dynamic contentDiv;
    public HtmlEditor(WebBrowser webBrowserControl, string htmlContent)
    {
        webBrowser = webBrowserControl;
        webBrowser.DocumentText = @"<div contenteditable=""true""></div>";
        webBrowser.DocumentCompleted += (s, e) =>
        {
            doc = webBrowser.Document.DomDocument;
            contentDiv = doc.getElementsByTagName("div")[0];
            contentDiv.innerHtml = htmlContent;
        };
    }
    public string HtmlContent => contentDiv.InnerHtml;
    public void Bold() { doc.execCommand("bold", false, null); }
    public void Italic() { doc.execCommand("italic", false, null); }
    public void Underline() { doc.execCommand("underline", false, null); }
    public void OrderedList() { doc.execCommand("insertOrderedList", false, null); }
    public void UnorderedList() { doc.execCommand("insertUnOrderedList", false, null); }
    public void ForeColor(Color color)
    {
        doc.execCommand("foreColor", false, ColorTranslator.ToHtml(color));
    }
    public void BackColor(Color color)
    {
        doc.execCommand("backColor", false, ColorTranslator.ToHtml(color));
    }
    public void InsertImage(Image image)
    {
        var bytes = (byte[])new ImageConverter().ConvertTo(image, typeof(byte[]));
        var src = $"data:image/png;base64,{Convert.ToBase64String(bytes)}";
        doc.execCommand("insertImage", false, src);
    }
    public void Heading(Headings heading)
    {
        doc.execCommand("formatBlock", false, $"<{heading}>");
    }
    public enum Headings { H1, H2, H3, H4, H5, H6 }
}

To use this HTML Editor class, it's enough to have a WebBrowsercontrol on a Formand initialize the editor this way:

要使用这个 HTML Editor 类,只需在 aWebBrowser上有一个控件Form并以这种方式初始化编辑器就足够了:

HtmlEditor editor;
private void Form1_Load(object sender, EventArgs e)
{
    var html = @"Some html content";
    editor = new HtmlEditor(webBrowser1, html);
}

Then you can use a ToolStripto show available commands and run the commands. For example:

然后您可以使用 aToolStrip来显示可用命令并运行这些命令。例如:

private void OrderedListButton_Click(object sender, EventArgs e)
{
    editor.OrderedList();
}

private void ImageButton_Click(object sender, EventArgs e)
{
    using (var ofd = new OpenFileDialog())
    {
        ofd.Filter = "Image files|*.png;*.jpg;*.gif;*.jpeg;*.bmp";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            using (var image = Image.FromFile(ofd.FileName))
            {
                editor.InsertImage(image);
            }
        }
    }
}