Click here to Skip to main content
15,868,440 members
Articles / Programming Languages / C#

A Windows Forms based text editor with HTML output

Rate me:
Please Sign up or sign in to vote.
4.91/5 (171 votes)
2 Jul 2013CPOL5 min read 2.7M   72.5K   412   462
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.

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

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

C#
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.

C#
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:

C#
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.

C#
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.

C#
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:

C#
IHTMLDocument2 doc = webBrowser1.Document.DomDocument as IHTMLDocument2;

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

C#
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.

C#
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalcopy an image doesn't show when copied from ms word Pin
netJP12L23-Jan-08 10:47
netJP12L23-Jan-08 10:47 
GeneralRe: copy an image doesn't show when copied from ms word Pin
canghaiyixiaowh20-Mar-08 17:05
canghaiyixiaowh20-Mar-08 17:05 
GeneralRe: copy an image doesn't show when copied from ms word Pin
Eysi24-Sep-09 22:17
Eysi24-Sep-09 22:17 
QuestionHow do I make this Readonly? Pin
kizhakk22-Jan-08 10:22
kizhakk22-Jan-08 10:22 
AnswerRe: How do I make this Readonly? Pin
BITS_UK4-Jun-08 0:19
BITS_UK4-Jun-08 0:19 
Questionvb.net Pin
_d_22-Dec-07 16:31
_d_22-Dec-07 16:31 
GeneralLinks to website now working Pin
pmaghnani11-Dec-07 0:34
pmaghnani11-Dec-07 0:34 
Generalthanks, but has bugs [modified] Pin
M.S. Babaei15-Nov-07 18:08
M.S. Babaei15-Nov-07 18:08 
GeneralRe: thanks, but has bugs Pin
Peter Gfader4-Dec-07 23:19
Peter Gfader4-Dec-07 23:19 
GeneralThanks Pin
lepipele17-Oct-07 11:18
lepipele17-Oct-07 11:18 
Generalthanks for the post Pin
salman kazi29-Sep-07 0:48
salman kazi29-Sep-07 0:48 
QuestionPlease reply!having problem about selection tag? Pin
mohadese3-Sep-07 1:45
mohadese3-Sep-07 1:45 
GeneralRetrieving a bookmark name Pin
fishysmile2-Sep-07 18:56
fishysmile2-Sep-07 18:56 
GeneralAdd CSS link to the document Pin
ruben ruvalcaba23-Aug-07 15:14
ruben ruvalcaba23-Aug-07 15:14 
NewsBetter way of handling selection change & any other DOM event Pin
John Hind20-Aug-07 1:38
John Hind20-Aug-07 1:38 
Generalsystem.invalidoperationexception [modified] Pin
Manoher13-Aug-07 6:55
Manoher13-Aug-07 6:55 
GeneralRe: system.invalidoperationexception Pin
Manoher16-Aug-07 6:38
Manoher16-Aug-07 6:38 
GeneralRe: system.invalidoperationexception Pin
sanong17-Aug-07 22:50
sanong17-Aug-07 22:50 
GeneralExactly what I was looking for, but need it in VB... Pin
Karl Rhodes11-Aug-07 2:16
Karl Rhodes11-Aug-07 2:16 
GeneralRe: Exactly what I was looking for, but need it in VB... Pin
Karl Rhodes13-Aug-07 10:44
Karl Rhodes13-Aug-07 10:44 
Hi all,

I've slowly been working my way through the code to VB.Net and almost have a working version.

Almost the only problem I have is the Body_KeyDown procedure.
There is a line that reads "if (EnterKeyEvent != null)" in the C# code and when I try to convert this line to VB ("If Not IsNothing(EnterKeyEvent) Then" or "If EnterKeyEvent IsNot Nothing Then") I get an error telling me EnterKeyEvent is an event and cannot be called directly. It also suggests I use a RaiseEvent statement to raise the event.

If I understand correctly, this code isn't actually trying to raise an event, but check if one has been raised already? If this is the case, how is this done in VB?

Thanks in advance

For reference I have included the C# and my VB converted code here...

C#
public event EventHandler<enterkeyeventargs> EnterKeyEvent;

private void Body_KeyDown(object sender, HtmlElementEventArgs e)
{
if (e.KeyPressedCode == 13 && !e.ShiftKeyPressed)
{
// handle enter code cancellation
bool cancel = false;
if (EnterKeyEvent != null) // Problem Line
{
EnterKeyEventArgs args = new EnterKeyEventArgs();
EnterKeyEvent(this, args);
cancel = args.Cancel;
}
e.ReturnValue = !cancel;
}
}


VB

Public Event EnterKeyEvent As EventHandler(Of EnterKeyEventArgs)

Private Sub Body_KeyDown(ByVal sender As Object, ByVal e As HtmlElementEventArgs)
If e.KeyPressedCode = 13 AndAlso Not e.ShiftKeyPressed Then
Dim cancel As Boolean = False
If Not IsNothing(EnterKeyEvent) Then 'Problem Line
Dim args As New EnterKeyEventArgs()
RaiseEvent EnterKeyEvent(Me, args)
cancel = args.Cancel
End If
e.ReturnValue = Not cancel
End If
End Sub

Karl

GeneralRe: Exactly what I was looking for, but need it in VB... Pin
DumBleBee27-Aug-07 3:36
DumBleBee27-Aug-07 3:36 
GeneralRe: Exactly what I was looking for, but need it in VB... Pin
John Couture25-Jan-08 4:41
John Couture25-Jan-08 4:41 
QuestionRe: Exactly what I was looking for, but need it in VB... Pin
Tim Stokes4-Oct-07 0:41
Tim Stokes4-Oct-07 0:41 
QuestionError when closing form Pin
thachvv1819-Jul-07 7:45
thachvv1819-Jul-07 7:45 
AnswerRe: Error when closing form Pin
shackrat24-Jul-07 4:07
shackrat24-Jul-07 4:07 

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.