Search code examples
c#browserrichtextboxwysiwyg

c# WYSIWYG editor using webbrowser and richtextbox


Im trying to hammer togehter a WYSIWYG-edit in c# following some examples from here and other place.

Im using a webbrowser for the design state of the editor, but i need to be able to switch to "html-view" so I used a rich textbox, and my tought was to just grab the content from the webbrowser and set it to the rtb, and the other way around.

It works fine until i try to put back the value from the rtb into the webbrowser, then i get a "This document has changed, do you want to save the changes"-alert and after that the webbrowser wont accept new content.

Any idea what to do? Or any other way to handle the solution im after?

the code:

namespace EmailAdmin
{
    public partial class Form1 : Form
    {

    // global variables
    private IHTMLDocument2 doc;
    private int WYSIWYGviewState = 0;

    public Form1()
    {
        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // initiate web browser to design mode
        webBrowserWYSIWYG.DocumentText = "<html><body></body></html>";
        doc = webBrowserWYSIWYG.Document.DomDocument as IHTMLDocument2;
        doc.designMode = "On";            
    }

    private void linkSwitchWYSIWYGview_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        // determins viewstate
        // is design view
        if (WYSIWYGviewState == 0)
        {
            // set html view
            WYSIWYGviewState = 1;
            rtbWYSIWYG.Visible = true;

            // populates the texteditor with html
            rtbWYSIWYG.Text = webBrowserWYSIWYG.DocumentText;

            // change label text
            linkSwitchWYSIWYGview.Text = "View Design";


        }
        // is html view
        else if (WYSIWYGviewState == 1)
        {
            // set design view
            WYSIWYGviewState = 0;
            rtbWYSIWYG.Visible = false;

            // populates the designer with html
            webBrowserWYSIWYG.DocumentText = rtbWYSIWYG.Text;

            // change label text
            linkSwitchWYSIWYGview.Text = "View HTML";
        }
    }
}
}

Solution

  • It's a good thing for you that I've spent far too much time recently looking at how the WebBrowser control and related things work :-)

    To do what you want, instead of

    webBrowserWYSIWYG.DocumentText = rtbWYSIWYG.Text;
    

    do

    webBrowserWYSIWYG.Document.Write(rtbWYSIWYG.Text);
    

    I hope that helps. It works for me.

    Edit: Try this:

    webBrowserWYSIWYG.Document.OpenNew(true);
    webBrowserWYSIWYG.Document.Write(rtbWYSIWYG.Text);