Click here to Skip to main content
15,886,919 members
Articles / Web Development / HTML
Tip/Trick

C# WPF WYSIWYG HTML Editor

Rate me:
Please Sign up or sign in to vote.
4.82/5 (23 votes)
28 Jan 2015CPOL2 min read 119.6K   9.1K   48   19
HTML WPF editor WYSIWYG (what you see is what you get).

Image 1

Introduction

In this tip, you will learn the use of WPF webbrowser control and the use of the library mhtml for editing. This simple example will also help you understand how the toolbar works in WPF.

Background

In the development of a WPF application, I needed to edit HTML documents. After extensive research on already existing solutions in WPF without finding my happiness, I finally decided to write my own HTML editor.
After analyzing Winform solutions, I found that Microsoft made significant changes in the WPF Webbrowser.
It is always possible to use WPF WindowsFormsHost, but you lose the benefits of WPF.
In the WPF version of the webbrowser, there is no more IsWebBrowserContextMenuEnabled, ActiveXInstance.
Ownership document has also been changed, the Winform version contains a document of type System.Windows.Forms.HtmlDocument with lots of interesting methods such as PointToClient and GetElementFromPoint.
In WPF webrowser, the document is a document object and you need to cast it to mshtml.HtmlDocument type.
The mshtml library is a very powerful library that offers great possibilities for editing and analyzing an HTML document.
The official documentation is very well stocked.
https://msdn.microsoft.com/en-us/library/aa753630%28v=vs.85%29.aspx

WPF Interface

The benefits of WPF technology are numerous and has the potential to create many advanced interfaces.
A future article will be devoted to Ribbon Toolbar in WPF.

Editing the HTML

To edit a document using Microsoft.mshtml library, it’s necessary to reference it in the project.

C#
using mshtml;

public void newDocument()
{
    webBrowser.NavigateToString(Properties.Resources.New);
    doc = webBrowser.Document as HTMLDocument;
    doc.designMode = "On";
}

Formatting the HTML

To change the heading of a selection, there are several ways to proceed.
This method uses FormatBlock webbrowser control.

C#
public static void RibbonComboboxFormat(ComboBox RibbonComboboxFormat)
{
    string ID = ((Items)(RibbonComboboxFormat.SelectedItem)).Value;

    webBrowser.doc = webBrowser.webBrowser.Document as HTMLDocument;
    if (webBrowser.doc != null)
    {
        webBrowser.doc.execCommand("FormatBlock", false, ID);
    }
}

Another solution is to use the library mshtml.

C#
mshtml.IHTMLDocument2 doc;

doc = webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;

mshtml.IHTMLTxtRange r = doc.selection.createRange() as mshtml.IHTMLTxtRange;
mshtml.IHTMLElement parent = r.parentElement();
mshtml.IHTMLElement heading = doc.createElement("<h2>");

r.pasteHTML(heading.outerHTML);

With the Appendchild webbrowser method, you can add elements such as tables or any other HTML too.

C#
HtmlElement tableElem = webBrowser1.Document.CreateElement("TABLE");
webBrowser1.Document.Body.AppendChild(tableElem);

To format the text, you can proceed in several different ways, either by using the webbrowser or the mshtml library.
In this example, I chose to use commands in the webbrowser.

C#
public static void InsertOrderedList(HTMLDocument doc)
{
    if (doc != null)
    {
        doc.execCommand("InsertOrderedList", false, null);
    }
}

Color Dialogbox in WPF

The dialog box Winform is incompatible with WPF.
WPF uses System.Windows.Media.Color and System.Windows.Media.Brush while Winform uses System.Drawing.Color.
The workaround is to made color transfer from the four channels individually.

Image 2

C#
public static System.Windows.Media.Color Pick()
{
    System.Windows.Media.Color col = new System.Windows.Media.Color();

    using (System.Windows.Forms.ColorDialog colorDialog = new System.Windows.Forms.ColorDialog())
    {
        colorDialog.AllowFullOpen = true;
        colorDialog.FullOpen = true;
        System.Windows.Forms.DialogResult result = colorDialog.ShowDialog();

        if (result == System.Windows.Forms.DialogResult.OK)
        {
            col.A = colorDialog.Color.A;
            col.B = colorDialog.Color.B;
            col.G = colorDialog.Color.G;
            col.R = colorDialog.Color.R;
        }
    }
    return col;
}

Supress the Script Error Message

For pages containing scripts, the webbrowser may generate errors, in the Winform version of the webbrowser, there is a ScriptErrorsSuppressed property that has unfortunately disappeared in the WPF webbrowser.

C#
// Property in the Winform version.

webBrowser.ScriptErrorsSuppressed = true;

It is necessary to implement this functionality in WPF webbrowser.

C#
using System.Reflection;

public static void HideScriptErrors(WebBrowser wb, bool Hide)
{
    FieldInfo FieldInfoComWebBrowser = typeof(WebBrowser).GetField
    ("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);

    if (FieldInfoComWebBrowser == null)
    { 
    return;
    }

    object ComWebBrowser = FieldInfoComWebBrowser.GetValue(wb);

    if (ComWebBrowser == null)
    { 
        return;
    }

    ComWebBrowser.GetType().InvokeMember("Silent", 
    BindingFlags.SetProperty, null, ComWebBrowser, new object[] { Hide });
}

Conclusion

Thanks for viewing this tip. I expect feedback from you.

License

This tip, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Belgium Belgium

Microsoft Certification Profile



Microsoft® Certified Professional
Microsoft® Specialist: Programming in C# (70-483)

http://www.mycertprofile.com/Profile/1706423521
Exam 483: Programming in C#

Articles


C# WPF WYSIWYG HTML Editor

Comments and Discussions

 
QuestionHtml change event Pin
Александр Рыбарук24-May-21 21:41
Александр Рыбарук24-May-21 21:41 
QuestionMSHTML documentation Pin
RonVanAken26-Apr-20 5:16
RonVanAken26-Apr-20 5:16 
QuestionFormatting (Heading, Paragraph, etc.) Pin
Pommersche9225-Mar-18 21:45
Pommersche9225-Mar-18 21:45 
AnswerRe: Formatting (Heading, Paragraph, etc.) Pin
Member 138497038-Aug-18 2:02
Member 138497038-Aug-18 2:02 
QuestionMSHTML Documentation has no C# Section? Pin
tolu61931-Mar-17 1:05
tolu61931-Mar-17 1:05 
Generalthank you very much for your work! Pin
Member 1238531215-Apr-16 3:24
Member 1238531215-Apr-16 3:24 
Questionunordered list bullet dots size Pin
nighttrain_23-Mar-16 9:41
nighttrain_23-Mar-16 9:41 
QuestionHow to add HTML tables to this? Pin
James Roneson16-Nov-15 3:17
James Roneson16-Nov-15 3:17 
QuestionHTML Table Editing Pin
James Roneson16-Nov-15 2:04
James Roneson16-Nov-15 2:04 
QuestionHTML All Uppercase Pin
Member 102502278-Sep-15 11:03
Member 102502278-Sep-15 11:03 
QuestionHow insert Video using this Editor Pin
Sandeep Khairha28-May-15 3:44
professionalSandeep Khairha28-May-15 3:44 
QuestionImport the html Editor as a dll in Gupta Team Developer 6.2 .Net for a WPF Custom Control Pin
AF-German13-Apr-15 7:24
AF-German13-Apr-15 7:24 
AnswerRe: Import the html Editor as a dll in Gupta Team Developer 6.2 .Net for a WPF Custom Control Pin
Yannick Turbang15-Apr-15 7:47
Yannick Turbang15-Apr-15 7:47 
GeneralRe: Import the html Editor as a dll in Gupta Team Developer 6.2 .Net for a WPF Custom Control Pin
AF-German9-May-15 23:45
AF-German9-May-15 23:45 
QuestionRe: Import the html Editor as a dll in Gupta Team Developer 6.2 .Net for a WPF Custom Control Pin
susad5-Jan-16 21:38
susad5-Jan-16 21:38 
Questionyou could share the full code sample Pin
Tridip Bhattacharjee28-Jan-15 20:33
professionalTridip Bhattacharjee28-Jan-15 20:33 
AnswerRe: you could share the full code sample Pin
Yannick Turbang28-Jan-15 23:08
Yannick Turbang28-Jan-15 23:08 
GeneralRe: you could share the full code sample Pin
Tridip Bhattacharjee29-Jan-15 20:38
professionalTridip Bhattacharjee29-Jan-15 20:38 
GeneralRe: you could share the full code sample Pin
Yannick Turbang29-Jan-15 22:00
Yannick Turbang29-Jan-15 22:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.