Click here to Skip to main content
Licence 
First Posted 12 Sep 2006
Views 445,940
Downloads 10,682
Bookmarked 280 times

A Windows Forms based text editor with HTML output

By kevin delafield | 25 Nov 2006
A Windows Forms based text editor with HTML output, implemented with a browser control in edit mode.
1 vote, 1.1%
1
1 vote, 1.1%
2
3 votes, 3.2%
3
7 votes, 7.4%
4
83 votes, 87.4%
5
4.89/5 - 96 votes
5 removed
μ 4.78, σa 1.13 [?]

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

kevin delafield



United States United States

Member


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

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionCannot write text on Windows 7 Ultimate Edition Pinmembermd_faisal21:46 24 Jan '12  
AnswerRe: Cannot write text on Windows 7 Ultimate Edition PinmemberGoran6523:13 26 Jan '12  
GeneralRe: Cannot write text on Windows 7 Ultimate Edition Pinmembermd_faisal0:49 28 Jan '12  
GeneralRe: Cannot write text on Windows 7 Ultimate Edition PinmemberGoran656:43 28 Jan '12  
QuestionActiveElement only return body Pinmemberaaaaali19:50 19 Dec '11  
QuestionLicense Pinmemberjustme_tony5:39 23 Nov '11  
QuestionDisplay Documents inside the WebBrowser PinmemberGeoNav6:11 18 Oct '11  
QuestionEnter Key Problem PinmemberGeoNav6:25 17 Oct '11  
QuestionProblem on Windows 7 PinmemberAvTwvHs22:37 11 Oct '11  
AnswerRe: Problem on Windows 7 PinmemberPierpaolo Romanelli3:26 1 Nov '11  
GeneralRe: Problem on Windows 7 Pinmemberjoao carlos batista6:22 7 Nov '11  
AnswerRe: Problem on Windows 7 Pinmemberjpsstavares8:03 7 Nov '11  
GeneralRe: Problem on Windows 7 PinmemberMember 10060080:32 19 Dec '11  
QuestionHow can lowercase all html tag on htmlview PinmemberTuanNGUYEN1:22 23 Sep '11  
QuestionSending mail with image PinmemberMember 82372166:54 19 Sep '11  
QuestionOverride Paste Behavior when using Ctrl+V PinmemberDiluk1:24 17 Aug '11  
GeneralInternet Explorer 9 PinsitebuilderUwe Keim20:41 27 Feb '11  
GeneralRe: Internet Explorer 9 Pinmemberquyhuu16:22 15 Mar '11  
GeneralRe: Internet Explorer 9 PinsitebuilderUwe Keim20:47 15 Mar '11  
GeneralRe: Internet Explorer 9 PinmemberPietro_SVK5:34 18 Apr '11  
GeneralRe: Internet Explorer 9 Pinmemberparvez1213:12 10 Jul '11  
GeneralRe: Internet Explorer 9 Pinmemberjpsstavares8:05 7 Nov '11  
GeneralRe: Internet Explorer 9 PinmemberFrancisco Freitas4:52 22 Nov '11  
GeneralRe: Internet Explorer 9 PinmemberMember 233376813:32 11 Dec '11  
GeneralMy vote of 5 PinmemberSpencerP6:50 22 Feb '11  

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

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

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