Simple HTML Editor Using WPF

HTML stands for

H : Hyper 
T : Text 
M : Markup 
L : Language.

The HTML language is an authoring language create documents on the World Wide Web (WWW). HTML defines the structure and layout of a web document using a variety of tags and attributes. HTML documents contain two things that are:

  1. HTML tags with their attributes
  2. Plain text

HTML was designed in 1992 by Tim Berners-Lee.

That is an explanation of HTML and its history.

Now let's explain what a HTML Editor is.

HTML Editor

HTML can be edited using a professional HTML editor like:

  • Adobe Dreamweaver
  • Microsoft Expression Web
  • CoffeeCup HTML Editor

We can also use Notepad (Windows PC) or TextEdit (Mac) to edit a HTML page. But our purpose is to create our own HTML Editor using WPF, that will better than NotePad and TextEdit.

Use the following procedure to create your own HTML Editor:

  1. Open Visual Studio and go to "File" -> "New" -> "Project..." or press Ctrl+Shift+N.
  2. Now select WPF Application from the Visual C# Templates and provide any name for the file, such as WPF_HTML_EDITOR.
  3. Now you will see the MainWindow.xaml file, as in the following:

    HTML Editor

  4. Now just drag and drop a TextBox using Toolbox onto the form. The TextBox will provide the vital role of editing our HTML text and increase its height and width of this TextBox because the TextBox should be Multiline.

    Note: In WPF, to get a Multiline TextBox you need to change some property of the TextBox because the TextBox is not multiline by default even if you change its width and height. 

    Go to the Property Window and set the properties as in the following:

    • TextWrapping as a "Wrap": This property arranges the texts written in the text box.
    • AcceptsReturn Check-Box as checked: This property gets or sets a value indicating whether pressing Enter in a multiline TextBox control creates a new line of text in the control or activates the default button for the form.
    • AcceptsTab Check-Box as checked: This property gets or sets a value indicating whether pressing the Tab key enters a Tab character into the control instead of moving the focus to the next control in the tab order. This is a dependency property.

    The following figure shows how to set the TextWrapping, AcceptsReturn and AcceptsTab properties:

    Property Window
     

  5. In the next step you need to create some Buttons and Combo Boxes to make this HTML Editor easier. I have created some buttons on the form that are:

    • NEW: This button creates a new HTML file.
    • OPEN: This button opens an already saved HTML file. 
    • SAVE: To save the HTML file at a specific location.
    • SAVE AS: To save the same copy of the file at a location with the same or a different name.
    • CLOSE: To close the opened HTML File.

HTML TAG BUTTONS: Some HTML Tag buttons I have also created are:

  • B: To make the text bold.
  • I: To make the text italicized.
  • U: To underline the text.
  • P: To create a paragraph.
  • Link: To create a link.
  • BR: To create a break; a </br> tag that breaks the HTML line.

For the heading tag and FormTag just drag and drop a ComboBox from the toolbox.

  • Heading Tag ComboBox: Insert some Items by using the Item property of a ComboBox. 

    Click on the Item property of the Heading ComboBox and add the following 7 items:

    --Heading--
    H1
    H2
    H3
    H4
    H5
    H6

    Note: The --Heading-- item is the default but it will not be used.
     
  • Form Tag ComboBox: This ComoBox will facilitate the design of any HTML Form to easily Insert some items using the Item property of the ComboBox. Click on the Item Property of the ComboBox and add the following items:

    --FORM TAGS--
    Form
    Text Box
    Password
    CheckBox
    Radio Button
    Button
    Drop Down
    Text Area

    Note: The --FORM TAGS-- item is the default but it will not be used.
     
  • Preview: Drag and Drop one button to see the preview of the designed HTML Document.

My Designed Form: The complete form I have designed is as follows.

Designing Window

That has explained the design part of the HTML editor. Now for the code.

When the HTML editor will be run some code will already exist in the TextBox; that code will be as follows:

<html>

<head>

    <title>MyWebsite1</title>

</head>

<body>

</body>

</html>

And also the save button will be disabled.

To get this code at runtime (by default) and the save button initially disabled you need to write the following code in the constructor of the MainWindow. The code is written as follows:
 

public MainWindow()

{

   InitializeComponent();

   SaveBtn.IsEnabled = false;

   //by default Save Button will be disable at the starting time

   textBox1.Text = "<HTML>\n\t<HEAD>\n\t\t<TITLE>MyWebsite1</TITLE>\n\t</HEAD>\n\n\n\t<BODY>\n\n\n\t</BODY>\n</HTML>";

}


After writing into the TextBox, the save button will be enabled so you need to write the following code on the TextChanged event of the TextBox.
 

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)

{

   SaveBtn.IsEnabled = true;

}


As I mentioned above, I have used some buttons and combo boxes so now I need to fire some events on the buttons and Combo Box. The following code is for creating a new file, opening a file, saving (and save-as) a file and close the file.

NEW


The following explains what is done on the Click event of the NEW button.

  1. Check whether the old file is saved
  2. If the file is not saved then first save the old file
  3. Otherwise create a new file 

The following is the code to do that (on the Click Event of the NEW button):

private void NewBtn_Click(object sender, RoutedEventArgs e)

{

   if (SaveBtn.IsEnabled == true)k

   {

         MessageBoxResult MsgBoxresult = MessageBox.Show("Do you want to save content or not",

         "Do you want to save file", MessageBoxButton.YesNo,MessageBoxImage.Question);

          if (MsgBoxresult == MessageBoxResult.Yes)

          {

              MainWindow obj = new MainWindow();

              Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

              sfd.DefaultExt = ".htm";

              sfd.Filter = "HTML File (.html)|*.html|

              HTM Files (.htm)|*.htm";

              if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)

              {

                 File.WriteAllText(sfd.FileName, textBox1.Text);

              }

         }

         textBox1.Text = string.Empty;

         SaveBtn.IsEnabled = false;

    }

}


OPEN

The following explains what is done on the Click event of the OPEN button.

  1. Check whether the old file is saved
  2. If the file has not been saved then first save the old file
  3. Otherwise open a new file 

The following is the code to do that (on the Click Event of the OPEN button):

private void OpenBtn_Click(object sender, RoutedEventArgs e)

{

   if (textBox1.Text != string.Empty)

   {

   MainWindow obj = new MainWindow();

   Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

   sfd.DefaultExt = ".htm";

   sfd.Filter = "HTML File (.html)|*.html| HTM Files (.htm)|*.htm";

      if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)

      {

      File.WriteAllText(sfd.FileName, textBox1.Text);

      savepath = sfd.FileName.ToString();

      save = true;

      }

   }

   Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

   ofd.DefaultExt = ".htm";

   ofd.Filter = "HTML File (.html)|*.html| HTM Files (.htm)|*.htm";

      if (ofd.ShowDialog() == true)

      {

      StreamReader StreamReader1 = new StreamReader(ofd.FileName, Encoding.Default);

      textBox1.Text = StreamReader1.ReadToEnd();

      save = true;

      savepath = ofd.FileName.ToString();

      }

   SaveBtn.IsEnabled = false;

   save = true;



CLOSE


The following explains what is done on the Click event of the CLOSE button.

  1. Check whether the old file is saved
  2. If the file has not been saved then first save the old file
  3. Otherwise close

The following is the code to do that (on the Click Event of the CLOSE button):

private void CloseBtn_Click(object sender, RoutedEventArgs e)

{

  if (SaveBtn.IsEnabled == true)

  {

  MessageBoxResult MsgBoxresult = MessageBox.Show("Do you want to save content or not",

  "Do you want to save file", MessageBoxButton.YesNoCancel, MessageBoxImage.Question);

      if (MsgBoxresult == MessageBoxResult.Yes)

      {

      MainWindow obj = new MainWindow();

      Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

      sfd.DefaultExt = ".htm";

      sfd.Filter = "HTML File (.html)|*.html| HTM Files (.htm)|*.htm";

         if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)

         {

         File.WriteAllText(sfd.FileName, textBox1.Text);

         }

      this.Close();

      }

      else if (MsgBoxresult == MessageBoxResult.No)

      {

      this.Close();

      }

      else

      {

      }

   }


SAVE

The following explains what is done on the Click event of the SAVE button.

  1. Check whether this file has already been saved.
  2. If it has already been saved then overwrite the file.
  3. If not then save it at the specific location after choosing from the save file dialog.

The following is the code to do that (on the Click Event of the SAVE button):

private void SaveBtn_Click(object sender, RoutedEventArgs e)

{

   if (save == false)

   {

   Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

   sfd.DefaultExt = ".htm";

   sfd.Filter = "HTML File (.html)|*.html| HTM Files (.htm)|*.htm";

      if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)

      {

      File.WriteAllText(sfd.FileName, textBox1.Text);

      savepath = sfd.FileName.ToString();

      save = true;

      }

   }

   else

   {

   File.WriteAllText(savepath, textBox1.Text);

   }


SaveAs:


The following explains what is done on the Click event of the SaveAS button:

  1. Directly save file at that location where you want to save.

The following is the code to do that (on the Click Event of the SAVE button):

private void SaveAsBtn_Click(object sender, RoutedEventArgs e)

{

    Microsoft.Win32.SaveFileDialog

    sfd = new Microsoft.Win32.SaveFileDialog();

    sfd.DefaultExt = ".htm";

    sfd.Filter = "HTML File (.html)|*.html| HTM Files (.htm)|*.htm";

    if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)

    {

        File.WriteAllText(sfd.FileName,textBox1.Text);

        savepath = sfd.FileName.ToString();

        save = true;

     }

}


Now the next code is for the HTML TAG buttons; the Buttons and Combo Boxes for the HTML EDITOR, that I have designed is shown in the following figure:

Buttons and Combo-Boxes for the HTML EDITOR

Bold Button (B): In HTML the bold tag can be defined as <B>.....</B> so on the click event of the Bold button provide the following code.
 

private void BoldBtn_Click(object sender, RoutedEventArgs e)

{

    textBox1.SelectedText = "<B>" + textBox1.SelectedText + "</B>";


Italic Button (I): In HTML the Italic tag can be defined as <I>.....</I> so on the click event of the Italic button provide the following code.

private void ItalicBtn_Click(object sender, RoutedEventArgs e)

{

    textBox1.SelectedText = "<I>" + textBox1.SelectedText + "</I>";



UnderLine Button (U): In HTML the UnderLine tag can be defined as <U>.....</U> so on the click event of the Underline button provide the following code.
 

private void UnderLineBtn_Click(object sender, RoutedEventArgs e)

{

    textBox1.SelectedText = "<U>" + textBox1.SelectedText + "</U>";


Paragraph Button (U): In HTML the Paragraph tag can be defined as <P>.....</P> so on the click event of the Paragraph tag button provide the following code.

 

private void UnderLineBtn_Click(object sender, RoutedEventArgs e)

{

    textBox1.SelectedText = "<P>" + textBox1.SelectedText + "</P>";


Break Button (U): In HTML the Break tag can be defined as </BR> so on the click event of the Break tag button provide the following code.

private void BtnBrak_Click(object sender, RoutedEventArgs e)

{

    var selectionIndex = textBox1.SelectionStart;

    string insertText = "</BR>";

    textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

    textBox1.SelectionStart = selectionIndex + insertText.Length;



Heading ComboBox: In HTML, there are 6 heading tags H1, H2,H3, H4, H5, H6 that can be written as:

<H1> HEADING-1 </H1>
<H2> HEADING-2 </H2>
<H3> HEADING-3 </H3>
<H4> HEADING-4 </H4>
<H5> HEADING-5 </H5>
<H6> HEADING-6 </H6>

You can write the following code for the heading tags on the SelectionChanged event of the ComboBox:
 

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)

{

   if (comboBox1.SelectedIndex != 0)

   {

     textBox1.SelectedText = "<H" + comboBox1.SelectedIndex + ">" + textBox1.SelectedText + "</H" +

     comboBox1.SelectedIndex + ">";

   }

}

LINK Button: The HTML <a> tag defines a hyperlink. A hyperlink (or link) is a word, group of words, or image that you can clicked on to jump to another document. When you move the cursor over a link in a Web page, the arrow will turn into a little hand. The most important attribute of the <a> element is the href attribute, that indicates the links destination. By default, links will appear as follows in all browsers:

  • An unvisited link is underlined and blue
  • A visited link is underlined and purple
  • An active link is underlined and red

HTML Link Syntax

The HTML code for a link is simple. It looks like this:

<a href="url">Link text</a>

The href attribute specifies the destination of a link.

Example

<a href="">Visit W3Schools</a>

So for a link tag you need to write the following code:

private void LinkBtn_Click(object sender, RoutedEventArgs e)

{

    if (save == false)

    {

    MessageBox.Show("Please Save The File First");

    }

    else

    {

    var selectionIndex = textBox1.SelectionStart;

    string insertText = "<a href=\"Please_Give_Link_of_File_Here\">Link_Name<a>";

    textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

    textBox1.SelectionStart = selectionIndex + insertText.Length;

    }


Form Tag ComboBox: HTML forms are used to pass data to a server. An HTML form can contain input elements like text fields, checkboxes, radio buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements. The <form> tag is used to create an HTML form. You can see the following code for the Form Tag ComboBox's SelectionChanged event:

private void FormTags_SelectionChanged(object sender, SelectionChangedEventArgs e)

{

    var selectionIndex = textBox1.SelectionStart;

    if (FormTags.SelectedIndex == 1)//form tag

    {

        string insertText = "<form

        name=\"Insert own name here\" action=\"Put Your action Here p\" method=\"post\">\n\n</form>";

        textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

        textBox1.SelectionStart = selectionIndex + insertText.Length;

    }

    else if (FormTags.SelectedIndex == 2)//textbox

    {

         string insertText = "<input type=\"text\" name=\"InsertNameHere\">";

         textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

         textBox1.SelectionStart = selectionIndex + insertText.Length;

    }

    else if (FormTags.SelectedIndex == 3)//Password

    {

        string insertText = "<input type=\"password\" name=\"pwd1\">";

        textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

        textBox1.SelectionStart = selectionIndex + insertText.Length;

    }

    else if (FormTags.SelectedIndex == 4)//CheckBox

    {

         string insertText = "<input type=\"checkbox\" name=\"Give_Name\" value=\"Give_Value\">Item_Name";

         textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

         textBox1.SelectionStart = selectionIndex + insertText.Length;

    }

    else if (FormTags.SelectedIndex == 5)//Radio

    {

       string insertText = "<input type=\"radio\" name=\"Give_Name\" value=\"Give_Value\">Item_Name"; textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

       textBox1.SelectionStart = selectionIndex + insertText.Length;

    }

    else if (FormTags.SelectedIndex == 6)//Button

    {

        string insertText = "<input type=\"submit\" value=\"Submit\">";

        textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

        textBox1.SelectionStart = selectionIndex + insertText.Length;

    }

    else if (FormTags.SelectedIndex == 7)//Drop Down

    {

        string insertText = "<select name=\"Selection_Name\">\n</br>

       <option value=\"1\">1</option>\n</br>

       <option value=\"2\">2</option>\n</br>

       <option value=\"3\">2</option>\n</br>

       <option value=\"4\">4</option>\n</br>

       <option value=\"5\">5</option>\n</br>

       </select>\n";

       textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

       textBox1.SelectionStart = selectionIndex + insertText.Length;

    }

    else if (FormTags.SelectedIndex == 8)//Text Area

    {

       string insertText = "<textarea rows=\"10\" cols=\"30\">Insert Text Here</textarea>";

       textBox1.Text = textBox1.Text.Insert(selectionIndex, insertText);

       textBox1.SelectionStart = selectionIndex + insertText.Length;

    }

    else

    {

    }

} 


Now the final code is for the Preview but before that you need to do create a new form for the preview. Use the following procedure to create the new form for the Preview:

  1. Open Solution Explorer 
  2. Right-click on your project's namespace.
  3. Then "Add" >> "New Items..." or (Ctrl + Shift +A)
  4. Select Windows (WPF) and add this to the project

I have named it "Preview.xaml". Now drag the "WebBrowser" tool from the ToolBox and drop onto the Preview.xaml Form.

Now in the "Preview.xaml.cs" write the following code in the constructor. 

public Preview(string filepath)

{

    InitializeComponent();

    webBrowser1.Navigate(new Uri(filepath));



Note: I created a parameterized constructor because we need to open a saved file (the HTML page code we have written in the HTML Editor TextBox). In this parameterized constructor I am passing my saved file path.

Now write the following code into the preview button of the HTML Editor (MainWindow.xaml.cs):
 

private void PreviewBtn_Click(object sender, RoutedEventArgs e)

{

    if (save == true)

    {

       Preview preview1 = new Preview(savepath);

       preview1.Show();

   }

   else

   {

      MessageBox.Show("Please First This Save Your File",

      "Save This HTML File", MessageBoxButton.OK, MessageBoxImage.Asterisk);

   }



Finally Output

The MainWindow will be like this:

Main output Window
 
The preview of the written code will be look like this:

Preview of the written code

Up Next
    Ebook Download
    View all
    Learn
    View all
    sourabhsomani.com