C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C# Expert!

Join 300,380 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,531 people online right now. Registration is fast and FREE... Join Now!




Creating a wysiwyg HTML editor in C#

 
Reply to this topicStart new topic

> Creating a wysiwyg HTML editor in C#, Using the MS HTML Object Library

aj32
Group Icon



post 7 Apr, 2008 - 06:22 AM
Post #1


Creating a wysiwyg HTML editor in C#

This tutorial will demonstrate how to create a wysiwyg (visual) HTML editor using IHTMLdocument2 class in mshtml.


The first thing we need to do is create a windows forms application in C#, using an IDE such as Visual Studio or SharpDevelop.

On the form, place a toolbar and a webbrowser control, such as shown below

IPB Image

Next, we need to set the properties of the webbrowser to make it work correctly in edit mode:

webbrowser properties:

AllowNavigation = false
Allowwebbrowserdrop = false
IsWebBrowserContextMenu = false
ScriptErrorsSuppressed = true
(Name) = HTMLEditor


All other settings can remain their default value


Now we need to add a reference to mshtml, do this by clicking the 'Project' menu bar item, and, from the drop down menu, click 'Add Reference'.
When the dialog appears, click the COM tab. Under that tab, scroll down untill you see 'Microsoft HTML Object Library', double click the object to add it.


Now that we have the reference to the HTML object library, which resolves to 'mshtml', just add a using mshtml; to our Form1.cs file.
Also, under public partial class Form1 : Form, add this global variable:
csharp

private IHTMLDocument2 doc;



Once this is done, go back to design mode, double click the top part of the form to create a Form1_Load()( event. In Form1_Load(), add the following code:

csharp

HTMLEditor.DocumentText = "<html><body></body></html>"; //This will get our HTML editor ready, inserting common HTML blocks into the document
//Make the web 'browser' an editable HTML field

doc =
HTMLEditor.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";
//What we just did was make our web browser editable!


We now have a fully enabled wysiwyg HTML editor!


Controlling the HTML Editor

Now that we have our editor set up, we need a way to edit the contents to the user's commands, add something to the toolbar we inserted a while ago, such as a bold button, font size selector, etc. For this tutorial, I am going to use a bold button and a font size selector.

IPB Image

Double-Click the Bold button, creating an onclick() event. You should be automatically switched to code view. In the event that was just created (eg. private void toolStripButton1_Click() ), add this to make the selected font bold:

csharp

HTMLEditor.Document.ExecCommand("Bold", false, null);


...and that's it, this will now make the selected text bold!

The first argument ("Bold") is, obviously, the command. The Second argument (false in this case) determines whether or not the pre-made dialog, that comes with mshtml, is shown. The third argument (null in this case) is the Object Value.


Do the same thing for the rest of the controls you have added to your toolbar, create your own WYSIWYG HTML editor!

Here is a list of some of the most common commands:
csharp

HTMLEditor.Document.ExecCommand("Bold", false, null);
HTMLEditor.Document.ExecCommand("Underline", false, null);
HTMLEditor.Document.ExecCommand("Italics", false, null);
HTMLEditor.Document.ExecCommand("StrikeThrough", false, null);
HTMLEditor.Document.ExecCommand("FontName", false, "Times New Roman");
HTMLEditor.Document.ExecCommand("FontName", false, "Arial");
HTMLEditor.Document.ExecCommand("FontName", false, "etc.");
HTMLEditor.Document.ExecCommand("FontSize", false, "1");
HTMLEditor.Document.ExecCommand("FontSize", false, "2");
HTMLEditor.Document.ExecCommand("FontSize", false, "3");
HTMLEditor.Document.ExecCommand("InsertUnorderedList", false, null);
HTMLEditor.Document.ExecCommand("InsertOrderedList", false, null);
HTMLEditor.Document.ExecCommand("Cut", false, null);
HTMLEditor.Document.ExecCommand("Copy", false, null);
HTMLEditor.Document.ExecCommand("Paste", false, null);
HTMLEditor.Document.ExecCommand("CreateLink", true, null);


//HERE IS THE WAY TO INSERT YOUR OWN TEXT INTO THE HTML EDITOR:


String TEXT = "YOUR TEXT GOES HERE!";

IHTMLTxtRange range =
doc.selection.createRange() as IHTMLTxtRange;
range.pasteHTML(TEXT);
range.collapse(false);
range.select();



There are a few more, but those are the most common ones!



Getting the HTML from the control



If you want your HTML editor to save the html to a .html file, just call the DocumentText from the webbrowser, like this:
csharp


String SAVECONTENTS = HTMLEditor.DocumentText;

//Continue, to save the contents to a file




This is the end of this tutorial! I hope this tutorial has been useful to you, and thanks for reading!
If you have any questions on this topic, feel free to ask!
-AJ32 smile.gif
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

aj32
Group Icon



post 23 May, 2008 - 09:22 AM
Post #2
I can't edit the tutorial, but I'll post some more of the HTML editor commands here:
(Most are self-explanatory)

csharp

//Images:
string IMGSRC = "http://www.example.com/example.jpg";
HTMLEditor.Document.ExecCommand("InsertImage", false, IMGSRC);

//LINK:
string URL = "http://www.example.com";
string Text = "Example.com";

IHTMLTxtRange range =
doc.selection.createRange() as IHTMLTxtRange;
range.pasteHTML("<A href=\"" + URL + "\">" + Text + "</A>");
range.collapse(false);
range.select();

//HR:
HTMLEditor.Document.ExecCommand("InsertHorizontalRule", false, null);

//ALIGN:
HTMLEditor.Document.ExecCommand("JustifyLeft", false, null);
HTMLEditor.Document.ExecCommand("JustifyRight", false, null);
HTMLEditor.Document.ExecCommand("JustifyCenter", false, null);
HTMLEditor.Document.ExecCommand("JustifyFull", false, null);




(if one of the mods could add that into the tutorial, that would be great wink2.gif )
Go to the top of the page
+Quote Post

A7med Baraka
*



post 14 Jul, 2008 - 03:01 AM
Post #3
when i add this

Now that we have the reference to the HTML object library, which resolves to 'mshtml', just add a using mshtml; to our Form1.cs file.
Also, under public partial class Form1 : Form, add this global variable:
csharpview plainprint?
private IHTMLDocument2 doc;


there is 2 errors appers
Error 1 The type or namespace name 'mshtml' does not exist in the namespace 'System' (are you missing an assembly reference?) Form1InterActive Book.cs 8 14

Error 2 The type or namespace name 'IHTMLDocument2' could not be found (are you missing a using directive or an assembly reference?) Form1InterActive Book.cs 14 17


but i am adding the reference as u said ??

any advice ??
Go to the top of the page
+Quote Post

aj32
Group Icon



post 14 Jul, 2008 - 04:47 AM
Post #4
QUOTE(A7med Baraka @ 14 Jul, 2008 - 07:01 AM) *

when i add this

there is 2 errors appers
Error 1 The type or namespace name 'mshtml' does not exist in the namespace 'System' (are you missing an assembly reference?) Form1InterActive Book.cs 8 14

Error 2 The type or namespace name 'IHTMLDocument2' could not be found (are you missing a using directive or an assembly reference?) Form1InterActive Book.cs 14 17


but i am adding the reference as u said ??

any advice ??


It looks like your are trying to add System.mshtml it is only mshtml (e.g. using mshtml;. Once you get that in place the IHTMLDocument2 error will go away (IHTMDocument2 is a part of mshtml).

Hope that helps. smile.gif
Go to the top of the page
+Quote Post

A7med Baraka
*



post 19 Jul, 2008 - 03:57 AM
Post #5
thnx i make it it should write MSHTML in capital
but i want to add audio , flash files ?? how can i make this
also i want to ask how i make the user inter the url of the image or the audio file or its location in the PC
Go to the top of the page
+Quote Post

Kirth
**



post 12 Sep, 2008 - 11:00 AM
Post #6
QUOTE(A7med Baraka @ 19 Jul, 2008 - 04:57 AM) *

also i want to ask how i make the user inter the url of the image or the audio file or its location in the PC


You could put those in a folder called "images" and get them uploaded with the user's files?
Go to the top of the page
+Quote Post

mmenon
*



post 29 Jan, 2009 - 07:47 AM
Post #7
QUOTE(A7med Baraka @ 14 Jul, 2008 - 03:01 AM) *

when i add this

Now that we have the reference to the HTML object library, which resolves to 'mshtml', just add a using mshtml; to our Form1.cs file.
Also, under public partial class Form1 : Form, add this global variable:
csharpview plainprint?
private IHTMLDocument2 doc;


there is 2 errors appers
Error 1 The type or namespace name 'mshtml' does not exist in the namespace 'System' (are you missing an assembly reference?) Form1InterActive Book.cs 8 14

Error 2 The type or namespace name 'IHTMLDocument2' could not be found (are you missing a using directive or an assembly reference?) Form1InterActive Book.cs 14 17


but i am adding the reference as u said ??

any advice ??





QUOTE(aj32 @ 7 Apr, 2008 - 06:22 AM) *

Creating a wysiwyg HTML editor in C#

This tutorial will demonstrate how to create a wysiwyg (visual) HTML editor using IHTMLdocument2 class in mshtml.


The first thing we need to do is create a windows forms application in C#, using an IDE such as Visual Studio or SharpDevelop.

On the form, place a toolbar and a webbrowser control, such as shown below

IPB Image

Next, we need to set the properties of the webbrowser to make it work correctly in edit mode:

webbrowser properties:

AllowNavigation = false
Allowwebbrowserdrop = false
IsWebBrowserContextMenu = false
ScriptErrorsSuppressed = true
(Name) = HTMLEditor


All other settings can remain their default value


Now we need to add a reference to mshtml, do this by clicking the 'Project' menu bar item, and, from the drop down menu, click 'Add Reference'.
When the dialog appears, click the COM tab. Under that tab, scroll down untill you see 'Microsoft HTML Object Library', double click the object to add it.


Now that we have the reference to the HTML object library, which resolves to 'mshtml', just add a using mshtml; to our Form1.cs file.
Also, under public partial class Form1 : Form, add this global variable:
csharp

private IHTMLDocument2 doc;



Once this is done, go back to design mode, double click the top part of the form to create a Form1_Load()( event. In Form1_Load(), add the following code:

csharp

HTMLEditor.DocumentText = "<html><body></body></html>"; //This will get our HTML editor ready, inserting common HTML blocks into the document
//Make the web 'browser' an editable HTML field

doc =
HTMLEditor.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";
//What we just did was make our web browser editable!


We now have a fully enabled wysiwyg HTML editor!


Controlling the HTML Editor

Now that we have our editor set up, we need a way to edit the contents to the user's commands, add something to the toolbar we inserted a while ago, such as a bold button, font size selector, etc. For this tutorial, I am going to use a bold button and a font size selector.

IPB Image

Double-Click the Bold button, creating an onclick() event. You should be automatically switched to code view. In the event that was just created (eg. private void toolStripButton1_Click() ), add this to make the selected font bold:

csharp

HTMLEditor.Document.ExecCommand("Bold", false, null);


...and that's it, this will now make the selected text bold!

The first argument ("Bold") is, obviously, the command. The Second argument (false in this case) determines whether or not the pre-made dialog, that comes with mshtml, is shown. The third argument (null in this case) is the Object Value.


Do the same thing for the rest of the controls you have added to your toolbar, create your own WYSIWYG HTML editor!

Here is a list of some of the most common commands:
csharp

HTMLEditor.Document.ExecCommand("Bold", false, null);
HTMLEditor.Document.ExecCommand("Underline", false, null);
HTMLEditor.Document.ExecCommand("Italics", false, null);
HTMLEditor.Document.ExecCommand("StrikeThrough", false, null);
HTMLEditor.Document.ExecCommand("FontName", false, "Times New Roman");
HTMLEditor.Document.ExecCommand("FontName", false, "Arial");
HTMLEditor.Document.ExecCommand("FontName", false, "etc.");
HTMLEditor.Document.ExecCommand("FontSize", false, "1");
HTMLEditor.Document.ExecCommand("FontSize", false, "2");
HTMLEditor.Document.ExecCommand("FontSize", false, "3");
HTMLEditor.Document.ExecCommand("InsertUnorderedList", false, null);
HTMLEditor.Document.ExecCommand("InsertOrderedList", false, null);
HTMLEditor.Document.ExecCommand("Cut", false, null);
HTMLEditor.Document.ExecCommand("Copy", false, null);
HTMLEditor.Document.ExecCommand("Paste", false, null);
HTMLEditor.Document.ExecCommand("CreateLink", true, null);


//HERE IS THE WAY TO INSERT YOUR OWN TEXT INTO THE HTML EDITOR:


String TEXT = "YOUR TEXT GOES HERE!";

IHTMLTxtRange range =
doc.selection.createRange() as IHTMLTxtRange;
range.pasteHTML(TEXT);
range.collapse(false);
range.select();



There are a few more, but those are the most common ones!



Getting the HTML from the control



If you want your HTML editor to save the html to a .html file, just call the DocumentText from the webbrowser, like this:
csharp


String SAVECONTENTS = HTMLEditor.DocumentText;

//Continue, to save the contents to a file




This is the end of this tutorial! I hope this tutorial has been useful to you, and thanks for reading!
If you have any questions on this topic, feel free to ask!
-AJ32 smile.gif


QUOTE


thanks for this excellent tutorial. I was able to implement it just fine. I was wondering if there was a way to embed this windows form application in an aspx page. I found out an object tag that can be used to insert windows control library, can the same approach be used for windows form application too ?



This post has been edited by mmenon: 29 Jan, 2009 - 07:44 AM
Go to the top of the page
+Quote Post

Public_account
*



post 13 Feb, 2009 - 07:09 AM
Post #8
The full list of commands

2D-Position

Allows absolutely positioned elements to be moved by dragging.
AbsolutePosition

Sets an element's position property to "absolute."
BackColor

Sets or retrieves the background color of the current selection.
BlockDirLTR

Not currently supported.
BlockDirRTL

Not currently supported.
Bold

Toggles the current selection between bold and nonbold.
BrowseMode

Not currently supported.
ClearAuthenticationCache

Clears all authentication credentials from the cache. Applies only to execCommand.
Copy

Copies the current selection to the clipboard.
CreateBookmark

Creates a bookmark anchor or retrieves the name of a bookmark anchor for the current selection or insertion point.
CreateLink

Inserts a hyperlink on the current selection, or displays a dialog box enabling the user to specify a URL to insert as a hyperlink on the current selection.
Cut

Copies the current selection to the clipboard and then deletes it.
Delete

Deletes the current selection.
DirLTR

Not currently supported.
DirRTL

Not currently supported.
EditMode

Not currently supported.
FontName

Sets or retrieves the font for the current selection.
FontSize

Sets or retrieves the font size for the current selection.
ForeColor

Sets or retrieves the foreground (text) color of the current selection.
FormatBlock

Sets the current block format tag.
Indent

Increases the indent of the selected text by one indentation increment.
InlineDirLTR

Not currently supported.
InlineDirRTL

Not currently supported.
InsertButton

Overwrites a button control on the text selection.
InsertFieldset

Overwrites a box on the text selection.
InsertHorizontalRule

Overwrites a horizontal line on the text selection.
InsertIFrame

Overwrites an inline frame on the text selection.
InsertImage

Overwrites an image on the text selection.
InsertInputButton

Overwrites a button control on the text selection.
InsertInputCheckbox

Overwrites a check box control on the text selection.
InsertInputFileUpload

Overwrites a file upload control on the text selection.
InsertInputHidden

Inserts a hidden control on the text selection.
InsertInputImage

Overwrites an image control on the text selection.
InsertInputPassword

Overwrites a password control on the text selection.
InsertInputRadio

Overwrites a radio control on the text selection.
InsertInputReset

Overwrites a reset control on the text selection.
InsertInputSubmit

Overwrites a submit control on the text selection.
InsertInputText

Overwrites a text control on the text selection.
InsertMarquee

Overwrites an empty marquee on the text selection.
InsertOrderedList

Toggles the text selection between an ordered list and a normal format block.
InsertParagraph

Overwrites a line break on the text selection.
InsertSelectDropdown

Overwrites a drop-down selection control on the text selection.
InsertSelectListbox

Overwrites a list box selection control on the text selection.
InsertTextArea

Overwrites a multiline text input control on the text selection.
InsertUnorderedList

Toggles the text selection between an ordered list and a normal format block.
Italic

Toggles the current selection between italic and nonitalic.
JustifyCenter

Centers the format block in which the current selection is located.
JustifyFull

Not currently supported.
JustifyLeft

Left-justifies the format block in which the current selection is located.
JustifyNone

Not currently supported.
JustifyRight

Right-justifies the format block in which the current selection is located.
LiveResize

Causes the MSHTML Editor to update an element's appearance continuously during a resizing or moving operation, rather than updating only at the completion of the move or resize.
MultipleSelection

Allows for the selection of more than one site selectable element at a time when the user holds down the SHIFT or CTRL keys.
Open

Not currently supported.
Outdent

Decreases by one increment the indentation of the format block in which the current selection is located.
OverWrite

Toggles the text-entry mode between insert and overwrite.
Paste

Overwrites the contents of the clipboard on the current selection.
PlayImage

Not currently supported.
Print

Opens the print dialog box so the user can print the current page.
Redo

Not currently supported.
Refresh

Refreshes the current document.
RemoveFormat

Removes the formatting tags from the current selection.
RemoveParaFormat

Not currently supported.
SaveAs

Saves the current Web page to a file.
SelectAll

Selects the entire document.
SizeToControl

Not currently supported.
SizeToControlHeight

Not currently supported.
SizeToControlWidth

Not currently supported.
Stop

Not currently supported.
StopImage

Not currently supported.
StrikeThrough

Not currently supported.
Subscript

Not currently supported.
Superscript

Not currently supported.
UnBookmark

Removes any bookmark from the current selection.
Underline

Toggles the current selection between underlined and not underlined.
Undo

Not currently supported.
Unlink

Removes any hyperlink from the current selection.
Unselect

Clears the current selection.
Go to the top of the page
+Quote Post

Christian!
*



post 18 Feb, 2009 - 04:23 AM
Post #9
Great tutorial! Works fine... icon_up.gif
Go to the top of the page
+Quote Post

wrighty
*



post 23 Mar, 2009 - 10:39 AM
Post #10
any screen shots of this in action?

i dont think mine is working

CODE
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mshtml;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    
        
    {
        private IHTMLDocument2 doc;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            HTMLEditor.DocumentText = "<html><body></body></html>";
            doc =
            HTMLEditor.Document.DomDocument as IHTMLDocument2;
            doc.designMode = "On";

        }
    }
}


thats my basic code is that correct?
Go to the top of the page
+Quote Post

wrighty
*



post 23 Mar, 2009 - 12:12 PM
Post #11
Give me a clue on the save using the
CODE
String SAVECONTENTS = HTMLEditor.DocumentText;

how do you call the rest of the save function?
Go to the top of the page
+Quote Post

RobinV
*



post 30 Mar, 2009 - 06:24 AM
Post #12
QUOTE(wrighty @ 23 Mar, 2009 - 12:12 PM) *

Give me a clue on the save using the
CODE
String SAVECONTENTS = HTMLEditor.DocumentText;

how do you call the rest of the save function?

Think before asking
Go to the top of the page
+Quote Post

wrighty
*



post 30 Mar, 2009 - 06:28 AM
Post #13
HAHA ops i think by that point it was getting on top of me all sorted now thanks
Go to the top of the page
+Quote Post

jammmie999
*



post 2 Apr, 2009 - 06:55 AM
Post #14
thanks for the great article see http://web.archive.org/web/20070108062548/.../commandids.asp for full list of functions
Go to the top of the page
+Quote Post

kamprasad
*



post 29 Apr, 2009 - 04:22 AM
Post #15
Hi,

thanks for this excellent tutorial


This editor can support the spelling check option ?



--kamprasad--
Go to the top of the page
+Quote Post

julanna
*



post 5 May, 2009 - 10:14 AM
Post #16
I have a question. I am working on a small website editor project and this post has been a great use to me.

The problem that I have is this: I open pages into the editor with a listBox that is populated from a directory. When I first start the app and click on a file to open in the editor it works fine. When i try to open another file into the editor it does nothing.

This is my code:

CODE
        

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            String file = listBox1.SelectedItem.ToString();
            HTMLEditor.DocumentText = System.IO.File.ReadAllText(file);
        }



How would I reset the editor "if that is what i should do" to open another file after I have opened the first one?
Go to the top of the page
+Quote Post

jammmie999
*



post 16 May, 2009 - 07:38 AM
Post #17
How do I use Relative links with this. When I type to insert a image at "images/myimage.php" it dont work. How can I make this work with out converting the link to Absolute.

Thanks
Go to the top of the page
+Quote Post

SanjitVignesh
*



post 17 May, 2009 - 06:56 AM
Post #18
QUOTE(julanna @ 5 May, 2009 - 10:14 AM) *

I have a question. I am working on a small website editor project and this post has been a great use to me.

The problem that I have is this: I open pages into the editor with a listBox that is populated from a directory. When I first start the app and click on a file to open in the editor it works fine. When i try to open another file into the editor it does nothing.

This is my code:

CODE
        

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            String file = listBox1.SelectedItem.ToString();
            HTMLEditor.DocumentText = System.IO.File.ReadAllText(file);
        }



How would I reset the editor "if that is what i should do" to open another file after I have opened the first one?



I had this same problem while designing my media player. The player does not play the one I click. Instead it plays the one I clicked before.
Go to the top of the page
+Quote Post

SBohnen
*



post 22 Jul, 2009 - 10:14 AM
Post #19
Great Solution!
Just wondering: The list of command identifiers:
http://web.archive.org/web/20070108062548/.../commandids.asp
does not include "insert table", so how could that be implemented?
Go to the top of the page
+Quote Post

Softwaredevelop
*



post 5 Nov, 2009 - 05:24 AM
Post #20
How to get the text entered in HTML Editor without HTML tags?
We can get text containing HTML tags with
HTMLEditor.DocumentTExt property
But how to get text withou tags in HTML Editor?
Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
3 User(s) are reading this topic (3 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/7/09 09:30PM

Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month