A WYSIWYG editor

In document in .NET (Page 126-134)

HTTP: Communicating with Web Servers

4.2 HTTP

4.2.7 A WYSIWYG editor

WYSIWYG (what you see is what you get) is a term used to describe Web and graphics editors that enable you to naturally manipulate graphical out-put, without having to be concerned with the underlying code. This feature is a handy way to let users be more creative in the type of textual messages or documents they create, without requiring them to take a crash course in HTML.

Internet Explorer can run in a special design mode, which is acceptable as a WYSIWYG editor. The trick to accessing design mode in Internet Explorer is simply to set the property WebBrowser.Document.designMode to

On. Users can type directly into the Internet Explorer window and use well-known shortcut keys to format text (e.g., Ctrl + B, Bold; Ctrl + I, Italic;

Ctrl + U, Underline). By right-clicking on Internet Explorer in design mode, a user can include images, add hyperlinks, and switch to browser mode. When an image is included in the design view, it can be moved and scaled by clicking and dragging on the edge of the image.

More advanced features can be accessed via Internet Explorer’s

execCommand function. Only FontName, FontSize, and ForeColor are used in the following sample program, but here is a list of the commands used by Internet Explorer.

Other functionality not included in this list can be implemented by dynamically modifying the underlying HTML.

To start coding this application, open a new project in Visual Studio .NET. Add a reference to Microsoft.mshtml by clicking Project→→Add Ref-→→ erence. Scroll down the list until you find Microsoft.mshtml, highlight it, and press OK. If you have not already done so from Chapter 1’s example, add Internet Explorer to the toolbox. To do this, right-click on the toolbox and select Customize Toolbox. Scroll down the list under the COM com-ponents tab until you see Microsoft Web Browser. Check the box opposite it, and press OK.

Table 4.6 Parameters of Internet Explorer’s execCommand function .

Command Meaning

Bold Inserts a <B> tag in HTML

Copy Copies text into the clipboard

Paste Pastes text from the clipboard

InsertUnorderedList Creates a bulleted list, <UL> in HTML Indent Tabulates text farther right on the page Outdent Retabulates text left on the page Italic Inserts an <I> tag in HTML Underline Inserts an <U> tag in HTML

CreateLink Creates a hyperlink to another Web page UnLink Removes a hyperlink from text

FontName Sets the font family of a piece of text FontSize Sets the font size of a piece of text CreateBookmark Creates a bookmark on a piece of text ForeColor Sets the color of the selected text SelectAll Is equivalent to pressing CTRL + A JustifyLeft Moves all text as far left as space allows JustifyRight Moves all text as far right as space allows

JustifyCenter Moves all selected text as close to the center as possible SaveAs Saves the page to disk

Draw a Tab control on the form named tabControl. Click on the

tabPages property in the properties window and add two tab pages, labeled Preview and HTML. Draw the Microsoft Web Browser control onto the preview tab page and name the control WebBrowser. Add three buttons to the Preview tab page, named btnViewHTML, btnFont, and btnColor. In the HTML tab page, add a textbox named tbHTML, and set its multiline prop-erty to true. Also add a button to the HTML tab page named btnPreview. Drag a Color Dialog control onto the form, and name it colorDialog. Drag a Font Dialog control onto the form and name it fontDialog.

Double-click on the form, and add the following code:

C#

private void Form1_Load(object sender, System.EventArgs e) {

object any = null;

object url = "about:blank";

WebBrowser.Navigate2(ref url,ref any,ref any,ref any,ref any);

Application.DoEvents();

((HTMLDocument)WebBrowser.Document).designMode="On";

}

VB.NET

Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs)

Dim url As Object = "about:blank"

WebBrowser.Navigate2( url) Application.DoEvents()

(CType(WebBrowser.Document, HTMLDocument)).designMode="On"

End Sub

In order to access the HTML contained within the Web browser page, it must first point to a valid URL that contains some HTML source. In this case, the URL about:blank is used. This page contains nothing more than

<HTML></HTML>, but is sufficient for the needs of this application. The

DoEvents method releases a little processor time to allow the Web browser to load this page. The Document property of the Web browser contains the object model for the page, but it must first be cast to an HTMLDocument

object to be of use. The designMode property of Internet Explorer is then set to On to enable WYSIWYG editing.

Click on the view HTML button on the Preview tab page and enter the following code:

C#

private void btnViewHTML_Click(object sender, System.EventArgs e)

{

tbHTML.Text=(

(HTMLDocument)WebBrowser.Document).body.innerHTML;

}

VB.NET

Private Sub btnViewHTML_Click(ByVal sender As Object, _ ByVal e As System.EventArgs)

tbHTML.Text= _

(CType(WebBrowser.Document, HTMLDocument)).body.innerHTML End Sub

This button extracts the HTML from the Web Browser control and places it into the HTML-viewer textbox. Again, the Document property must be cast to an HTMLDocument object in order to access the page object model. In this case, the body.innerHTML property contains the page source.

If you required the page source less the HTML tags, then body.innerText

would be of interest.

Click on the corresponding Preview button on the HTML tab page, and enter the following code:

C#

private void btnPreview_Click(object sender, System.EventArgs e)

{

((HTMLDocument)WebBrowser.Document).body.innerHTML=

tbHTML.Text;

}

VB.NET

Private Sub btnPreview_Click(ByVal sender As Object, _ ByVal e As System.EventArgs)

(CType(WebBrowser.Document, _

HTMLDocument)).body.innerHTML=tbHTML.Text End Sub

This code simply performs the reverse of the preceding code, replacing the HTML behind the Web browser with the HTML typed into the text-box.

Click on the Font button on the Preview tab page, and enter the follow-ing code:

C#

private void btnFont_Click(object sender, System.EventArgs e) {

fontDialog.ShowDialog();

HTMLDocument doc = (HTMLDocument)WebBrowser.Document;

object selection= doc.selection.createRange();

doc.execCommand("FontName",false, fontDialog.Font.FontFamily.Name);

doc.execCommand("FontSize",false,fontDialog.Font.Size);

((IHTMLTxtRange)selection).select();

}

VB.NET

Private Sub btnFont_Click(ByVal sender As Object, _ ByVal e As System.EventArgs)

fontDialog.ShowDialog()

Dim doc As HTMLDocument = CType(WebBrowser.Document, _ HTMLDocument)

Dim selection As Object = doc.selection.createRange() doc.execCommand("FontName",False,fontDialog.Font. _ FontFamily.Name)

doc.execCommand("FontSize",False,fontDialog.Font.Size) (CType(selection, IHTMLTxtRange)).select()

End Sub

Pressing the Font button will bring up the standard font dialog box (Figure 4.4), which allows the user to select any font held on the system and its size. Other properties that may be available on this screen, such as sub-script, strikethrough, and so on, are not reflected in the WYSIWYG editor.

This works by first capturing a reference to any selected text on the screen using the selection.createRange() method. The execCommand method is called twice, first to apply the font family to the selected text and then the font size. The selection is then cast to an IHTMLTxtRange interface, which exposes the select method and commits the changes to memory.

Now click on the Color button on the Preview tab page, and enter the following code:

C#

private void btnColor_Click(object sender, System.EventArgs e)

{

colorDialog.ShowDialog();

string colorCode = "#" +

toHex(colorDialog.Color.R) + toHex(colorDialog.Color.G) + toHex(colorDialog.Color.B);

HTMLDocument doc = (HTMLDocument)WebBrowser.Document;

object selection = doc.selection.createRange();

doc.execCommand("ForeColor",false,colorCode);

((IHTMLTxtRange)selection).select();

}

VB.NET

Private Sub btnColor_Click(ByVal sender As Object, _ Figure 4.4

Font-chooser dialog box.

ByVal e As System.EventArgs) colorDialog.ShowDialog() String colorCode = "#" + _

toHex(colorDialog.Color.R) + _ toHex(colorDialog.Color.G) + _ toHex(colorDialog.Color.B)

Dim doc As HTMLDocument = CType(WebBrowser.Document, _ HTMLDocument)

Dim selection As Object = doc.selection.createRange() doc.execCommand("ForeColor",False,colorCode)

(CType(selection, IHTMLTxtRange)).select() End Sub

Pressing the Color button brings up the standard Color dialog box (Fig-ure 4.5). When a color is chosen, the selected color is applied to any selected text. This code brings up the Color dialog box by calling the

Show-Dialog method. The color returned can be expressed in terms of its red (R), green (G), and blue (B) constituents. These values are in decimal format, in the range 0 (least intense) to 255 (most intense). HTML expresses colors in the form #RRGGBB, where RR, GG, and BB are hexadecimal equivalents

Figure 4.5 Color-picker dialog box.

of the R, G, and B values. To give a few examples, #FF0000 is bright red,

#FFFFFF is white, and #000000 is black.

Once again, a handle to the selected text is obtained in the same way as before. The execCommand method is called and passed ForeColor, along with the HTML color code. The selected text is cast to an IHTMLTxtRange

interface and committed to memory with the Select method as before.

The above code calls the function toHex to convert the numeric values returned from the colorDialog control to hexadecimal values, which are required by Internet Explorer. Enter the following code:

C#

public string toHex(int digit) {

string hexDigit = digit.ToString("X");

if (hexDigit.length == 1){

hexDigit = "0" + hexDigit;

}

return hexDigit;

}

VB.NET

Public Function toHex(ByVal number As Integer) As String Dim hexByte As String

hexByte = Hex(number).ToString() If hexByte.Length = 1 Then hexByte = "0" & hexByte End If

Return hexByte End Function

Finally, the relevant namespaces are required:

C#

using mshtml;

VB.NET

Imports mshtml

To test this application, run it from Visual Studio .NET. Type into the Web Browser control under the Preview tab. Press the Font button to change the style and size of any text that is selected. Press the Color button to change the color of selected text. You can insert images by right-clicking and selecting Insert image (special thanks to Bella for posing for this photo-graph!). Press the view HTML button, then switch to the HTML tab page to view the autogenerated HTML (Figure 4.6).

In document in .NET (Page 126-134)