Click here to Skip to main content
14,242,971 members

A Windows Forms based text editor with HTML output

Rate this:
4.92 (161 votes)
Please Sign up or sign in to vote.
4.92 (161 votes)
2 Jul 2013CPOL
A Windows Forms based text editor with HTML output, implemented with a browser control in edit mode.

 

NOTICE: As of 10/28/2017, a new version is available. 

Includes the following features:

  • Requires .NET 4.5.1.
  • Fixes save as and load bugs that fired browser dialogs.
  • Insert inline images either by URL or through the file system. File system images are embedded in the resulting HTML.
  • Full programmatic access to HTML, Body HTML, Body Text
  • Set the background color of the body.
  • Insert images.
  • Resize images.
  • Add and edit hyperlinks from text.
  • Add and edit hyperlinks from images.
  • Support for Windows XP SP2 to Windows 8.
  • Support for all versions of IE. 

 

 

Sample Image - editor.png

 

Introduction

A while ago, I was working on a chat application where one of the chat clients was web based and written with ASP.NET 2.0. The other chat client was a Windows Forms based .NET application written in C#. I needed a rich text editor for my WinForms client that could output HTML, so that the ASP.NET client could display the formatting from the WinForms client. This was ruled out while using the RTF text box.

The solution I worked out was to use a WebBrowser control in edit mode within my WinForms client. Formatting buttons on a toolbar above the web browser are synchronized to the current selection in the WebBrowser control.

This article explains solutions to most of the issues involved in building an editor control from a WebBrowser control. I won't go into everything, as the source code isn't that difficult to browse. But, I do cover some of the tricks necessary to get this to work.

Using the Control

The control is an executable.

You can run it directly with it's main form, or you can embed it as a control in your own app.

To embed it into your own app, simply reference the EXE as if it were a DLL from your app in Visual Studio. 

It should show up in the Toolbox Window in Visual Studio.  

Check the source code for examples of how to access it from your code.

It's a .NET 2.0 control, so it should work in older projects. 

Setting Design Mode 

Applying design mode and establishing an editing template for the document occurs automatically when using the component. But, for reference, here is a brief explanation of how it works.

Applying design mode requires using a COM interface: adding a reference to "Microsoft HTML Object Library", which resolves to MSHTML, and adding a 'using' of 'MSHTML'.

It is necessary to add a body to the control before you can apply changes to the DOM document. To do this, you can simply apply some text to the DocumentText property of the WebBrowser control.

webBrowser1.DocumentText = "<html><body></body></html>"

Next, get a reference to the new DomDocument COM interface, and set the design mode to "On".

IHTMLDocument2 doc =
webBrowser1.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";

Finally, I replace the context menu for the web browser control so the default IE browser context menu doesn't show up.

webBrowser1.Document.ContextMenuShowing += 
new HtmlElementEventHandler(Document_ContextMenuShowing);

The browser is now in design mode, with a custom method to display the context menu.

Applying Formatting

You can apply formatting and editor functions to a browser control in design mode with the ExecCommand method on browser.Document.

Here are several examples:

public void Cut()
{
    webBrowser1.Document.ExecCommand("Cut", false, null);
}
public void Paste()
{
    webBrowser1.Document.ExecCommand("Paste", false, null);
}
public void Copy()
{
    webBrowser1.Document.ExecCommand("Copy", false, null);
}

Some commands will toggle the formatting state of the current selection.

public void Bold()
{
    webBrowser1.Document.ExecCommand("Bold", false, null);
}

public void Italic()
{
    webBrowser1.Document.ExecCommand("Italic", false, null);
}

Synchronizing Formatting Buttons with Selected Text

This is a bit more tricky than applying formatting commands to the browser control. I literally query the state of the browser editor selection every 200 ms, and set the toolbar formatting buttons based on this.

private void timer_Tick(object sender, EventArgs e)
{
    SetupKeyListener();
    boldButton.Checked = IsBold();
    italicButton.Checked = IsItalic();
    underlineButton.Checked = IsUnderline();
    orderedListButton.Checked = IsOrderedList();
    unorderedListButton.Checked = IsUnorderedList();
    linkButton.Enabled = SelectionType == SelectionType.Text;

    UpdateFontComboBox();
    UpdateFontSizeComboBox();
    if (Tick != null) Tick();
}

You'll notice that there is a Tick event that is fired at the end of the timer's tick event. External components can subscribe to this event to update the state of their GUI. For example, they may update the Enabled state of cut/copy/paste/undo/redo buttons based on the state of the Editor control.

I do this by using the COM document interface retrieved from the WebBrowser control with:

IHTMLDocument2 doc = webBrowser1.Document.DomDocument as IHTMLDocument2;

Then I use queryCommandState to determine the state of the current selection:

public bool IsBold()
{
    return doc.queryCommandState("Bold");
}

public bool IsItalic()
{
    return doc.queryCommandState("Italic");
}

public bool IsUnderline()
{
    return doc.queryCommandState("Underline");
}

The link button and font controls are managed in a similar way, but I'll leave that for you to check out in the code.

Focusing

Focusing the control isn't necessarily simple either. The WebBrowser control itself will not accept focus. Neither will the WebBrowser control's document. But, the body will focus, assuming there is a body element on the control.

private void SuperFocus()
{
    if (webBrowser1.Document != null && 
        webBrowser1.Document.Body != null)
      webBrowser1.Document.Body.Focus();
}

Of course, you never need to call this method directly. Calling the Focus method on the control will place the focus on the editor control containing the WebBrowser control. The editor control will transfer focus to the WebBrowser's document body automatically, when it receives the GotFocus event.

Retrieving Text or HTML

The BodyHtml and BodyText methods retrieve the body HTML and text, respectively.

Linking to the Component Assembly

In Visual Studio 2005, you can link to an assembly (add a reference), even if the assembly is an executable. The editor is written as a component embedded in a form, so you can add this component to the control palette and drag and drop into your application. The control's name is Editor, under namespace Design.

Conclusion

The .NET 2.0 WebBrowser control can effectively be used as a text editor. This is useful when you need an editor control that can be used as an HTML editor. The implementation is not completely straightforward in some areas. This article attempts to show some of the tricks necessary to get it to work.

History

  • 10/04/2006 - various bug fixes and design updates / designer support.
  • 10/19/2006 - more bug fixes and more designer support.
  • 10/28/2017 - Upgrade to .net 4.5.1 and VS 2015

License

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

Share

About the Author

kevin delafield
United States United States
No Biography provided

Comments and Discussions

 
QuestionHow to insert custom tags at specific location Pin
fawaddd11-Mar-10 20:31
memberfawaddd11-Mar-10 20:31 
AnswerRe: How to insert custom tags at specific location [modified] Pin
JefJ0hnson19-Aug-10 11:31
memberJefJ0hnson19-Aug-10 11:31 
GeneralThank you, Pin
TopiTopi7-Feb-10 22:01
memberTopiTopi7-Feb-10 22:01 
Questionhow add background image Pin
sat_nar18-Nov-09 3:02
membersat_nar18-Nov-09 3:02 
GeneralDIV Tag Tables Pin
MatthysDT17-Nov-09 21:22
memberMatthysDT17-Nov-09 21:22 
GeneralFind and Replace Pin
friendprach9-Nov-09 23:57
memberfriendprach9-Nov-09 23:57 
GeneralAbout setting default FONt as Tahoma for the editor Pin
friendprach9-Nov-09 23:22
memberfriendprach9-Nov-09 23:22 
GeneralRe: About setting default FONt as Tahoma for the editor Pin
p3@nut29-Aug-10 22:22
memberp3@nut29-Aug-10 22:22 
Hi There!

Have you found a solution to your problem?I am experiencing the same problem, need to set default front to Tahoma.

Regards

Meyer
GeneralIntercept drag and drop events Pin
Gilvinit8-Nov-09 20:41
memberGilvinit8-Nov-09 20:41 
GeneralThank you very much dear Pin
kumar4u4u21-Oct-09 5:58
memberkumar4u4u21-Oct-09 5:58 
Questionhow can i eliminate Pin
hasan_um_ferdowsi14-Oct-09 21:33
grouphasan_um_ferdowsi14-Oct-09 21:33 
QuestionImage resizing in the control Pin
Mike Fuchs4-Aug-09 1:42
memberMike Fuchs4-Aug-09 1:42 
AnswerRe: Image resizing in the control Pin
Mike Fuchs4-Aug-09 2:53
memberMike Fuchs4-Aug-09 2:53 
Generalvb.net Pin
Yuan Marquez29-Jul-09 20:16
memberYuan Marquez29-Jul-09 20:16 
GeneralRe: vb.net [modified] Pin
SSDiver211224-May-10 12:57
memberSSDiver211224-May-10 12:57 
GeneralYour code will not work anymore under Vista.(in am using vista 64 bit) Pin
Diing7-Jul-09 21:49
memberDiing7-Jul-09 21:49 
QuestionHow to Implement spell checking? Pin
bkv796-Jul-09 4:42
memberbkv796-Jul-09 4:42 
QuestionGetting the selected element on right click Pin
smitch1285-Jul-09 16:26
membersmitch1285-Jul-09 16:26 
QuestionDocumentText value gets modified following assignment in Form Load event? Pin
DdoubleD27-Jun-09 0:58
memberDdoubleD27-Jun-09 0:58 
AnswerRe: DocumentText value gets modified following assignment in Form Load event? Pin
programmor2-Feb-12 4:44
memberprogrammor2-Feb-12 4:44 
Answeredit html link Pin
dnk.nitro27-May-09 5:45
memberdnk.nitro27-May-09 5:45 
GeneralRe: edit html link Pin
skyline9220-Jun-09 9:27
memberskyline9220-Jun-09 9:27 
QuestionLimiting the amount of text in the webbrowser control Pin
Gil Rodriguez27-May-09 4:12
memberGil Rodriguez27-May-09 4:12 
Generalthank you Pin
khaled-mcsd15-May-09 22:34
memberkhaled-mcsd15-May-09 22:34 
QuestionGot "DRAGDROP_E_NOTREGISTERED" Exception Pin
Jati Indrayanto3-May-09 17:28
memberJati Indrayanto3-May-09 17:28 

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.

Article
Posted 12 Sep 2006

Stats

2.3M views
64.3K downloads
402 bookmarked