Click here to Skip to main content
Click here to Skip to main content

A Windows Forms based text editor with HTML output

By , 11 Nov 2012
 

NOTICE: As of 11/11/2012, a fully functioning commercial version of this component, with support, is available at http://www.liveswitch.com

Includes the following features:

  • 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.

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.

License

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

About the Author

kevin delafield
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionhttp://www.liveswitch.com is not workingmemberndennisv19 May '13 - 0:50 
QuestionError: Trying to revoke a drop target that has not been registered (Exception from HRESULT: 0x80040100 (DRAGDROP_E_NOTREGISTERED))memberFarhan Hussain16 May '13 - 3:10 
QuestionCannot add control to existing projectmemberMachaira29 Apr '13 - 4:00 
QuestionCannot get the source files to open or the demo to runmemberJeff Dressing27 Mar '13 - 12:35 
AnswerRe: Cannot get the source files to open or the demo to runmemberkevin delafield27 Mar '13 - 15:45 
QuestionCan not init html content in editor. Can any help.memberThomas.TangLin3 Mar '13 - 22:45 
AnswerRe: Can not init html content in editor. Can any help.memberkevin delafield27 Mar '13 - 15:49 
GeneralRe: Can not init html content in editor. Can any help.memberBobishKindaGuy16 May '13 - 6:22 
QuestionGreat Articlememberashishgupta121226 Feb '13 - 19:07 
QuestionHow to cleae the cache?memberqiupengyuan6 Jan '13 - 20:31 
AnswerRe: How to cleae the cache?memberkevin delafield27 Mar '13 - 15:48 
NewsSupported commercial version now available.memberkevin delafield11 Nov '12 - 12:01 
GeneralMy vote of 5memberMember 16437928 Sep '12 - 6:33 
QuestionDrag & Drop ImagesmemberKantabriko26 Aug '12 - 15:31 
AnswerRe: Drag & Drop Imagesmemberkevin delafield27 Mar '13 - 15:51 
Questionwin7下不能编写memberguoyunshui_2007@sina.com22 Jul '12 - 23:47 
QuestionMinor Bug in this control font size automatically set to 0memberSourav Kumar Sinha3 Jun '12 - 22:00 
GeneralRe: Minor Bug in this control font size automatically set to 0memberpdnash3 Jul '12 - 0:32 
QuestionI can't type anything in this editor at run timemembermj_developer9 May '12 - 20:14 
QuestionWin7下不能编写memberyangshaokai2 May '12 - 16:54 
NewsThanksmembervioiii19 Apr '12 - 0:08 
QuestionHTML Editor Error plz help its urgentmembersonu878 Apr '12 - 22:38 
QuestionFont Sizememberprogrammor12 Mar '12 - 9:06 
QuestionEventsmemberMember 78109626 Mar '12 - 4:38 
QuestionCannot write text on Windows 7 Ultimate Editionmembermd_faisal24 Jan '12 - 20:46 
AnswerRe: Cannot write text on Windows 7 Ultimate EditionmemberGoran6526 Jan '12 - 22:13 
GeneralRe: Cannot write text on Windows 7 Ultimate Editionmembermd_faisal27 Jan '12 - 23:49 
GeneralRe: Cannot write text on Windows 7 Ultimate EditionmemberGoran6528 Jan '12 - 5:43 
GeneralRe: Cannot write text on Windows 7 Ultimate Editionmemberveeramani narayanasamy11 Jul '12 - 15:26 
GeneralRe: Cannot write text on Windows 7 Ultimate Editionmemberchayaphum11 May '12 - 19:16 
GeneralRe: Cannot write text on Windows 7 Ultimate Editionmemberdansjrp3 Sep '12 - 8:48 
GeneralRe: Cannot write text on Windows 7 Ultimate EditionmemberMember 29807123 Sep '12 - 23:54 
GeneralRe: Cannot write text on Windows 7 Ultimate Editionmembermailtorakib4 Oct '12 - 17:24 
QuestionActiveElement only return bodymemberaaaaali19 Dec '11 - 18:50 
QuestionLicensememberjustme_tony23 Nov '11 - 4:39 
QuestionDisplay Documents inside the WebBrowsermemberGeoNav18 Oct '11 - 5:11 
QuestionEnter Key ProblemmemberGeoNav17 Oct '11 - 5:25 
QuestionProblem on Windows 7memberAvTwvHs11 Oct '11 - 21:37 
AnswerRe: Problem on Windows 7memberPierpaolo Romanelli1 Nov '11 - 2:26 
GeneralRe: Problem on Windows 7memberjoao carlos batista7 Nov '11 - 5:22 
AnswerRe: Problem on Windows 7memberjpsstavares7 Nov '11 - 7:03 
GeneralRe: Problem on Windows 7memberMember 100600818 Dec '11 - 23:32 
QuestionHow can lowercase all html tag on htmlviewmemberTuanNGUYEN23 Sep '11 - 0:22 
QuestionSending mail with imagememberMember 823721619 Sep '11 - 5:54 
QuestionOverride Paste Behavior when using Ctrl+VmemberDiluk17 Aug '11 - 0:24 
GeneralInternet Explorer 9sitebuilderUwe Keim27 Feb '11 - 19:41 
GeneralRe: Internet Explorer 9memberquyhuu15 Mar '11 - 15:22 
GeneralRe: Internet Explorer 9sitebuilderUwe Keim15 Mar '11 - 19:47 
GeneralRe: Internet Explorer 9memberPietro_SVK18 Apr '11 - 4:34 
GeneralRe: Internet Explorer 9memberparvez1210 Jul '11 - 12:12 

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 11 Nov 2012
Article Copyright 2006 by kevin delafield
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid