Click to return to the DHTML, HTML     
Web Workshop  |  DHTML, HTML & CSS

DHTML Editing Component

This document describes technologies that are available in Internet Explorer 5. An earlier version of the DHTML Editing Component that is compatible with Internet Explorer 4.01 is available as an SDK that you can download from here.

Microsoft Corporation

Updated June 11, 1999

Welcome to the Microsoft® Dynamic HTML Editing Component (DHTML Editing Component) documentation. This documentation is designed to help application developers, script authors, and Web developers use the DHTML Editing Component to build applications and use the ActiveX Editing Control.

The DHTML Editing Component documentation is divided into the following sections:

Overview of the DHTML Editing Component

The Microsoft Dynamic HTML (DHTML) Editing Component allows Web authors and application developers to add WYSIWYG DHTML editing capabilities to their Web sites and applications. The editing component uses Microsoft's Component Object Model (COM) technology to provide access to editing services such as basic HTML formatting, tables, undo and redo, and absolute positioning.

The DHTML Editing Component uses Microsoft® Internet Explorer to parse and render HTML, so the editing environment provides a faithful representation of what the document will look like in the browser. Web authors and developers can use any language, including Visual Basic®, Visual Basic Scripting Edition (VBScript), JScript™, C, C++, and Java to access editing services and provide a user interface for editing features.

Web authors and developers can also access the DHTML document object model (DOM) to add sophisticated, custom editing features to their applications. If you begin with existing HTML, the DHTML Editing Component will preserve your original formatting (the original white space and tags will remain). In addition, you can edit pages created with Active Server Pages technology seamlessly, without changing the original server script.

In this section of the documentation, you can find the following general information about the DHTML Editing Component:

Sample Applications

A number of sample applications are available that illustrate the DHTML Editing Component. You can use the sample applications to see the component in action and get ideas for your own applications. They can also be used as tutorials that illustrate how to use both the DHTML Editing Component document object (DocObject) and ActiveX control.

All sample applications include both executable code and source code. To get the samples, visit the MSDN Online Samples site at http://www.microsoft.com/downloads/sample s/. Display the table of contents (TOC), open the node for Reusing Browser Technology, and then select the sample called DHTML Editing Control.

The Gallery contains a live sample that you can run directly as a Web application. It also offers a downloadable file that contains additional samples that illustrate how to use the DHTML Editing Component in Visual Basic and C-based applications.

When you download the sample file, the samples are installed in a directory called \SAMPLES beneath the root directory you specified. In the \SAMPLES directory are further directories, one for each standalone sample application, and another directory tree for the sample applications written as Web applications.

For details about the sample applications, see the Samples.htm file in the \SAMPLES directory.

See Also

Using the DHTML Editing Component Document Object, Using the DHTML Editing Control

DHTML Editing Component Features

The DHTML component includes editing features that allow even novice HTML users to create sophisticated Web pages. Editing features include:

Note For an example of how to implement drag-and-drop functionality with the DHTML Editing Component as the drop target, see the HTMLDrop sample application. For more details about sample applications, see "Sample Applications" under Overview of the DHTML Editing Component.

See Also
Types of DHTML Editing Components, Editing and Browsing Documents, Selecting Elements, Working with Absolutely Positioned Elements

Requirements

The DHTML Editing Component requires Microsoft Internet Explorer 5. In fact, the component is an integral part of Internet Explorer 5, and if you have the browser installed, the component is already available to you.

Note Early beta versions of Internet Explorer 5 did not contain the DHTML Editing Component. Be sure you have upgraded to the released version of Internet Explorer 5.

Using Internet Explorer 5 in Distributed Applications

If you are creating applications that will be distributed to other users, they, too, must have Internet Explorer 5 installed. If you are distributing standalone applications, such as an application written in Visual Basic, you can test for Internet Explorer 5 during the installation of your product, and if necessary, install it as part of your application. For details, see Deploying Applications that Use the DHTML Editing Component.

If Internet Explorer 5 is Not Practical

Two scenarios might make it impractical for you to require Internet Explorer 5:

In these cases, do not develop your application using the Internet Explorer 5 version of the DHTML Editing Component. Instead, use Internet Explorer 4 and use the earlier version of the DHTML Editing Component. The earlier version can be downloaded as an SDK from http://www.microsoft .com/workshop/author/dhtml/edit/download.asp. The earlier version supports almost all the functionality of the current version, and you can upgrade from the earlier to the current version without code changes at a later time.

Note The earlier version of the DHTML Editing control requires Internet Explorer 4; other browsers are not supported. The downloadable SDK includes documentation on how to install and distribute the Internet Explorer 4 version of the control.

Include and Header Files

Using the DHTML Editing Component requires certain header and include files. For example, the constants used to specify commands for the DHTML Editing control are defined in include files. There are header and include files specific to the language you are programming in, as listed in the following table:

Language Include/Header files
C or C++ Files for use with the DHTML Editing Component Doc Object:
  • Triedcid.h Command IDs.
  • Triedit.h File generated by midl.exe that provides access to TriEdit Doc Object control interfaces.
  • Triedit.idl Midl.exe source file, to be included in your IDL files if required. Also provides more human-readable interface definitions than Triedit.h.
  • triediid.h CLSID and IID GUIDs for the TriEdit Doc Object.
Files for use with the DHTML Editing control:
  • Dhtmled.h File generated by midl.exe that provides access to DHTML Editing control interfaces.
  • Dhtmled.idl Midl.exe source file, to be included your IDL files if required. Also provides more human-readable interface definitions than Dhtmled.h.
  • Dhtmliid.h CLSID and IID GUIDs for the DHTML Editing control.
JavaScript or Microsoft JScript
  • Dhtml.js Command IDs and other constants for using the DHTML Editing control.
Visual Basic or Visual Basic, Scripting Edition (VBScript)
  • Dhtml.vbs Command IDs, error codes and other constants for using the DHTML Editing control.
Visual Basic (as distinct from VBScript) does not require the Dhtml.vbs file to use command IDs. However, it is useful to have the Dhtml.vbs file as a source for creating a module to define error constants. For details, see Handling Errors in the DHTML Editing Control.
Note There are no include files required if you are using the DHTML Editing control in Visual J++.

You can get the header and include files two ways:

To download the Internet Explorer 5 headers and libraries

    1. Point your browser to: http://msdn.microsoft.com/downloads/samples/internet/setup/entry.htm.

    2. In the Welcome to MSDN Online Web Workshop Tools & Samples Download Area page, at the bottom (in the frame), choose Next. A list of downloadable files appears.

    3. Select the following for downloading:

    • Headers and Libraries for Internet Explorer 5.0
    • Win32 Headers and Libraries
    To use the libraries, follow the instructions on how to set up the order of header file and library paths on the Welcome to MSDN Online Web Workshop Tools & Samples Download Area page.

    What's New for the DHTML Editing Component in Internet Explorer 5

    The following list summarizes changes and improvements made for the DHTML Editing Component in Internet Explorer 5:

    Compatibility Between Versions

    If you have developed an application using an earlier version of the DHTML Editing Component, it is compatible with the current version, and you do not need to make any code changes. (There are very slight changes in the user interface for documents, as noted in the list above.) Note that the current version of the component requires Internet Explorer 5, and that any users of an application based on the current version of the component must have Internet Explorer 5 installed on their computer. More details are provided in Deploying Applications that Use the DHTML Editing Component.

    If users have an application based on the older version of the DHTML Editing Component and upgrade from Internet Explorer 4 to Internet Explorer 5, the Internet Explorer 5 installation process replaces their copies of Triedit.dll and DHTMLEd.ocx during the upgrade. If users uninstall Internet Explorer, the old versions of these files are rolled back.

    Developing an application with the DHTML Editing Component using Internet Explorer 5 and then running the application under Internet Explorer 4 is not supported. If you are not sure that your users will be running Internet Explorer 5, you should develop the application using the Internet Explorer 4 version of the DHTML Editing Component. This version is available as a downloadable SDK from http://www.microsoft .com/workshop/author/dhtml/edit/download.asp, which includes complete documentation and samples. Be sure to download and install the SDK onto a computer that uses Internet Explorer 4, not Internet Explorer 5.

    Types of DHTML Editing Components

    The DHTML Editing Component is available in two ways:

    In both cases, the component provides a default editing environment. Users can type text into the component, which automatically maintains the text in WYSIWYG format, displaying it appropriately.

    Note The component allows users to work directly with the <BODY> portion of a document. However, the DHTML Editing Component provides programmatic access to the entire document.

    The component supports a wide variety of formatting and editing capabilities, typically as property settings, methods, or commands that can be executed against the editing component itself or against the selection in it. Typically, you add a user interface to the component to make the features available to the user. For example, you might create menus and a toolbar to make character and paragraph formatting commands available to users.

    See Also

    Cr eating Toolbars and Menus for the DHTML Editing Control, Editing and Browsing Documents, Selecting Elements, Working with Absolutely Positioned Elements

    Editing and Browsing Documents

    The DHTML Editing Component supports two modes for working with a document: Edit mode and Browse mode. Both modes display the <BODY> portion of the document, but differ slightly in how they show it and in how the user can interact with the document.

    Note Browse mode is not available in the version of the DHTML Editing control that is marked as safe for scripting. For more details, see The DHTML Editing Component and Browser Security.

    To switch between Edit mode and Browse mode

    The differences between Edit mode and Browse mode are:

    In Browse mode, the document cannot directly be edited. However, you can programmatically manipulate the document using the DHTML object model, available via the IHTMLDocument2 interface in the document object or the DOM property in the control.

    If you are using the DHTML Editing control, methods that apply to the document as a whole, such as Load Document and NewDo cument, and so on, still work.

    Most properties of the DHTML Editing control are available in both Edit mode and Browse mode. For most properties, you can set a value in one mode, and that value is retained in the other. However, in some instances, such as ShowDet ails property, setting a property value has no effect in Browse mode. The documentation for each property indicates whether it is available in Edit mode and Browse mode, and whether it applies to Browse mode.

    See Also

    Mo difying Documents Using the DHTML Document Object Model

    Working with Absolutely Positioned Elements

    Dynamic HTML includes cascading style sheet (CSS) features that allow HTML elements to be absolutely positioned on a page, independent of their position within the HTML stream. An absolutely positioned HTML element has its CSS POSITION style attribute set to absolute instead of static. Absolutely positioned elements also have a z-index, which specifies the visual order of overlapping absolutely positioned elements and how absolutely positioned elements are ordered relative to elements in the HTML stream.

    Note For a complete discussion of absolute positioning, see the topic on Positioning on the MSDN Online Web site.

    Statically positioned elements are also referred to as 1-D elements. Relatively positioned elements (whose POSITION style attribute is set to relative) are treated as 1-D elements.

    The DHTML Editing Component provides commands for working with absolutely positioned elements. These editing commands can be used to:

    Note For an example of how to implement drag-and-drop functionality with the DHTML Editing Component as the drop target, see the HTMLDrop sample application. For more details about sample applications, see "Sample Applications" under Overview of the DHTML Editing Component.

    The following elements can be absolutely positioned:

    APPLET BUTTON DIV
    EMBED HR IFRAME
    IMG INPUT MARQUEE
    OBJECT SELECT SPAN
    TABLE TEXTAREA FIELDSET

    The absolutely positioned editing commands will have no effect on elements other than these. Absolute positioning does not apply to design-time controls.

    Statically positioned elements can be converted to be absolutely positioned, and vice-versa. It is not possible to do this using the DHTML object model because the IHTMLElement position attribute is read-only. Executing the IDM_TRIED_MAKE_ABSOLUTE or DECMD_MAKE_ABSOLUTE commands is the primary means of converting elements between 1-D and 2-D. (Elements can also be pasted from the Clipboard as absolutely positioned elements.)

    Changing the Z-Index

    You can call commands to change the z-index of the selected absolutely positioned element relative to the other absolutely positioned elements in its container. These commands modify the selected element's z-index as listed below.

    You can display a 1-pixel border around <DIV> elements and tables that are absolutely positioned (using the document object IDM_TRIED_SHOWBORDERS command or DHTML Editing control ShowBor ders property). The border is drawn around an element even if its BORDER attribute is set to zero. The border does not affect page layout.

    Moving Absolutely Positioned Elements

    When the DHTML Editing Component is in Edit mode, the user can move an absolutely positioned element by selecting it and dragging it to a specific position on the page. After an element has been positioned the Editing Component updates the element's LEFT and TOP style attributes to reflect the new position.

    Absolutely positioned elements can also be nudged, which moves them a specified distance. In the document object, the IDM_TRIED_NUDGE_ELEMENT command nudges the element. In the DHTML Editing control, elements can be nudged a pixel at a time using the arrow keys.

    To prevent them from being moved accidentally, absolutely positioned elements can be locked in position. When an element is locked, inadvertent mouse movement or arrow keys will not move them, nor can they be moved using the document object's nudge command. The locked state of an element is persisted into the HTML stream by adding a DESIGN_TIME_LOCK attribute to the style of the element. This means that lock attributes will be retained, even when a document is saved and reopened.

    Specifying Snap-To-Grid Positioning

    The DHTML Editing Component provides an invisible grid to aid the user in positioning elements. You can toggle snap-to-grid behavior on and off as required.

    Absolutely positioned elements jump from cell to cell of the grid as they are dragged in a table. Grid cell dimensions may be sized in pixel granularity. In the DHTML Editing control, grid cells are sized to 50x50 pixels by default, but can be altered. In the document object, use the IDM_TRIED_SET_ALIGNMENT command to enable the grid and set the grid cell size. In the DHTML Editing control, use the SnapToGr id, SnapToG ridX, and SnapToG ridY properties.

    Selecting Elements

    To work with elements on the page, you usually must first select them. The DHTML Editing component selection model resembles the Microsoft® Office 97 selection model. It has two fundamental types of selectable elements:

    Note For more information on absolutely positioned elements, see Working with Absolutely Positioned Elements.

    Note The DHTML Editing Component does not support multiple selection. All elements to be selected must be contiguous in the document.

    The sections below discuss how users can select elements in the document through the document's user interface. Elements can also be selected as text programmatically, using the DHTML document object model. For details about doing so in the Editing Component's document object, see Mo difying Documents Using the DHTML Document Object Model. For details about doing so in the DHTML Editing control, see Accessing the DHTML Document Object Model.

    UI Activation

    Directly selectable elements that display text support UI activation, which is an editing mode in which the textual content of the element can be edited directly. For example, by making a button control UI active, you can edit the button's caption by typing in the button instead of editing its caption property in the Properties window. (You can also still use the Properties window to edit the caption.)

    To edit an element using UI activation

    You can specify whether ActiveX controls, Java applets, and design-time controls are UI activated by setting the ActivateActiveXControls, Act ivateApplets, and Activa teDTCs properties.

    Working with Directly Selectable Containers

    There are two types of directly selectable elements:

    Tip Tables and <DIV> elements without borders can display a border in Edit mode if the IDM_TRIED_SHOWBORDERS command has been executed or the ShowBor ders property is set to True.

    To select directly selectable elements

    Selecting Text

    The following table describes selection behavior for text.

    Note Glyphs displayed by the IDM_TRIED_SHOWDETAILS command and the ShowDet ails property are treated like the surrounding text. For details about glyphs, see Displaying Glyphs for Non-Visual Elements.
    To perform this action Use this gesture
    Select multiple characters. Click and drag over text. Dragging beyond a word boundary selects whole words.
    Select text between insertion point and mouse pointer SHIFT+click
    Select a word Double-click. Dragging thereafter selects whole words.
    Select a paragraph Triple-click or CTRL+Double-click. Dragging thereafter selects whole paragraphs.
    Move or copy selection Select text; release mouse; and then drag to new location. Dragging with the left mouse button moves text. Dragging with the right mouse button displays a menu to move or copy.

    Note If dragged to an existing paragraph, text takes on the paragraph's attributes.

    Selecting Areas Containing Directly Selectable Elements and Text

    Mixed selections are treated like text. Directly selectable elements are selected completely and treated as a single text character. A drag that starts outside of a directly selectable element causes the entire element to be selected.

    Drag selection outside of a directly selectable element is always done in the 1-D stream. Absolutely positioned elements are selected based on their position in the 1-D stream. When the special glyph representing an absolutely positioned element's anchor point in the 1-D stream is selected, the absolutely positioned element is also selected.

    Dragging Elements

    A selection can be dragged to a new location in the document. The effect of the drag operation depends on the type of elements being dragged:

    Displaying Glyphs for Non-Visual Elements

    Because the DHTML Editing Component is a WYSIWYG editor, certain HTML elements are not normally visible. By default, the editor displays only the elements that you would see in a browser. For example, if the page contains HTML comments (enclosed in <!-- and --> ), the editor does not display them.

    To make these non-visual elements visible, you can specify that the editor display glyphs to mark the location of these elements. This helps avoid inadvertently deleting the elements--for example, by backspacing over them.

    Note When elements in the page are being selected, glyphs are treated like the surrounding text. For details, see Selecting Elements.

    Glyphs are not displayed by default. A host can selectively enable glyphs to be displayed. Glyphs are treated the same as text as far as selection goes.

    To enable and disable glyphs in the editor

    The glyphs that appear in the editor depend on whether the editor is being used with Microsoft Internet Explorer 4 or Internet Explorer 5. The following table lists the glyphs that the editor can display if Internet Explorer 5 is installed on the computer.

    Glyph Represents
    comments.gif HTML comment (<!-- through -->)
    div_begin.gif Beginning of division (<DIV> tag)
    div_end.gif End of division (</DIV> tag)
    p_end.gif Beginning of paragraph (<P> tag)
    p_end.gif End of paragraph (</P> tag)
    span_begin.gif Beginning of span (<SPAN> tag)
    span_end End of span (</SPAN> tag)
    br.gif Line break (<BR> tag)
    form_begin.gif Beginning of form (<FORM> tag)
    form_end.gif End of form (<FORM> tag)
    client_script.gif Script in the <BODY> portion of the document. This can include client script block (<SCRIPT>)and inline server script block in .asp files (<% %>, or <SCRIPT RUNAT="Server">).
    style.gif Style element (<STYLE>)
    anchor_with.gif Anchor point for absolutely positioned elements and for image elements that are aligned left or right (for example, <IMG ALIGN=RIGHT>). The glyph appears where the HTML tag defining the element is located in the HTML document.
    unknown_tag.gif Unrecognized HTML tags and unmatched ending tags

    The following table lists the glyphs that the editor can display if Internet Explorer 4 is installed on the computer. Not all the glyphs available in Internet Explorer 5 are available in Internet Explorer 4.

    Glyph Represents
    [cs4Y311 1267 bytes] HTML comment (<!-- through -->).
    [cs4Y312 2943 bytes ] Script in the <BODY> portion of the document. This can include client script block (<SCRIPT>), inline server script block in .asp files (<% %>, or <SCRIPT RUNAT="Server">).
    [cs4Y314 2943 bytes ] Style element (<STYLE>)
    [cs4Y313 2943 bytes ] <NOFRAMES> tag, used to specify alternate content for browsers that do not support frames.
    [cs4Y316 2943 bytes ] Anchor point for absolutely positioned elements and for image elements that are aligned left or right (for example, <IMG ALIGN=RIGHT>). The glyph appears where the HTML tag defining the element is located in the HTML document.
    [cs4Y315 2943 bytes ] Unrecognized HTML tags and unmatched ending tags.

    The DHTML Editing Component and Browser Security

    To allow the DHTML Editing control to be used in secure Web applications, the DHTML Editing Component includes two versions of the ActiveX editing control: one is marked as "safe for scripting," the other is not.

    The safe-for-scripting version is typically used in public Web-based applications. It is written to guarantee that the control cannot be used in any way that compromises a user's system, no matter how its properties are set, its methods are called, or its events are handled. This means that the control cannot read or write to the user's disk or registry, call another object with a higher security rating (such as an applet), or use any memory or system resources outside a browser's control. The control is also limited to opening only those documents that are in the same domain as the hosting Web page. It cannot open documents on a local drive. Finally, the safe-for-scripting control also does not support server redirection of URLs.

    <

    The version not marked safe for scripting does not have these safeguards. It is designed to be used in standalone applications where distribution and deployment is typically under more scrutiny than in Web-based applications. It is more often used with non-Web applications, such as those created in Microsoft Visual Basic or Microsoft Visual C++.

    When creating your application and choosing a version of the control to use, think carefully about the features the application requires and how the application will be accessed and used. It is also suggested that you test your application extensively to be sure that the version you've selected works as you expect.

    To conform to Web application standards, the safe-for-scripting version of the control does not support reading or writing directly to disk, and does not support printing. The following list indicates the features of the DHTML Editing control that are not available in the safe-for-scripting version:

    In addition, the LoadURL method supports only HTTP and FTP protocols, and it allows users to load documents only if they are in the same domain as the host page.

    All other features are the same.

    Deploying Applications that Use the DHTML Editing Component

    The current version of the DHTML Editing Component is part of Microsoft Internet Explorer 5, which includes both the DHTML document object and the DHTML Edit control. When you deploy your application, you do not need to include the DHTML Editing Component, because it is a system component on the user's computer.

    Note Early beta versions of Internet Explorer 5 did not contain the DHTML Editing Component. You must be sure that you are working with the released version of Internet Explorer 5.

    If you have developed your application using Internet Explorer 5, you must be sure that your users also have it. The following sections provide suggestions for how to test for Internet Explorer 5. If you are developing an application that might be used on a computer where Internet Explorer 5 is not installed, you must either provide a way for users to get Internet Explorer 5, or use a different development strategy. See "What To Do If Internet Explorer 5 Is Not Installed" below for details.

    Checking for Internet Explorer 5 in a Standalone Application

    If your application is a standalone application (not a Web-based application running in Internet Explorer 5), your setup program should check to see if Internet Explorer 5 is already installed on the user's computer. One way is to check the Windows Registry on the user's computer. Open this key:

    HKEY_LOCAL_MACHINE
      Software
        Microsoft
          Internet Explorer
    

    In this key, get the contents of the Version value, which will have Internet Explorer version information in a string with this format:

    <major>.<minor>.<build number>.<subbuild
    number>
    

    In your setup program, you should get the major version number - the number before the first period - and make sure it is "5" or above. Note that this is a string, even though it represents a number.

    Checking for Internet Explorer 5 In a Web Page

    If your application is Web-based, you should test whether the user's browser is Internet Explorer 5. Use a JavaScript script to get the use rAgent property of the na vigator object. If the user's browser is Internet Explorer, the string "MSIE" will appear as a substring. The version number can be further extracted from the userAgent string.

    The following illustrates a sample script that checks that the browser is Internet Explorer and that the version number if 5 or higher.

    <SCRIPT TYPE="text/javascript">
    if (navigator.userAgent.indexOf("MSIE") == -1){
       // Non-IE browser, navigate to a different page
    }
    else{
       // IE browser, now test for version 5 or better
       var browserVersionInfo = Array()
       browserVersionInfo = navigator.userAgent.split(";")
       IEVersion = browserVersionInfo[1].substring(6,7)
       if(IEVersion <"5"){ alert("This page requires Internet Explorer
    5!") // Navigate to a different page } } </SCRIPT>
    

    What To Do If Internet Explorer 5 Is Not Installed

    If Internet Explorer 5 is not installed on the user's computer, your options depend on the type of application you have and how you want to distribute it:

    If it is impractical to require Internet Explorer 5 as part of your application, you can use the earlier version of the DHTML Editing Component, which works with Internet Explorer 4. However, you must also develop your application using the older version - you cannot develop your application using the current version of the component and then distribute it using the older version.

    The older version of the DHTML Editing Component can be downloaded as an SDK that includes the necessary components, documentation, and samples. It is avalable from this Web site: http://www.microsoft .com/workshop/author/dhtml/edit/download.asp. For details about differences between version 1 and the current version, see What's New for the DHTML Editing Component in Internet Explorer 5.

    Keyboard Accelerators

    The DHTML Editing Component supports the following keyboard accelerators:

    Movement

    Description Key
    Move one character to the right. If an absolutely positioned element is selected, nudge the element one pixel to the right. RIGHT ARROW
    Move one character to the left. In the DHTML Editing control, if an absolutely positioned element is selected, nudge the element one pixel to the left. LEFT ARROW
    Move down one line. In the DHTML Editing control, if an absolutely positioned element is selected, nudge the element down one pixel. DOWN ARROW
    Move up one line. In the DHTML Editing control, if an absolutely positioned element is selected, nudge the element up one pixel. UP ARROW
    Move right one word CTRL+RIGHT ARROW
    Move left one word CTRL+LEFT ARROW
    Move to the end of the current line END
    Move to the start of the current line HOME
    Move down one paragraph CTRL+DOWN ARROW
    Move up one paragraph CTRL+UP ARROW
    Move down one page PAGE DOWN
    Move up one page PAGE UP
    Move to the beginning of the document CTRL+HOME
    Move to the end of the document CTRL+END
    Cycle selection through block-level elements within the control TAB
    Reverse-cycle selection through block-level elements within the control SHIFT+TAB
    Move from the control to the next element in the host application* CTRL+TAB
    Move from the control to the previous element in the host application* SHIFT+CTRL+TAB

    * These keystrokes do not work in host applications that support MDI windows. In those applications, the host application will use these keystrokes to move between MDI child windows.

    Selection

    Description (Command) Key
    Extend the selection one character to the right SHIFT+RIGHT ARROW
    Extend the selection one character to the left SHIFT+LEFT ARROW
    Extend the selection right one word CTRL+SHIFT+RIGHT ARROW
    Extend the selection left one word CTRL+SHIFT+LEFT ARROW
    Extend the selection up one line SHIFT+UP ARROW
    Extend the selection down one line SHIFT+DOWN ARROW
    Extend the selection to the end of the current line SHIFT+END
    Extend the selection to the start of the current line SHIFT+HOME
    Extend the selection down one page SHIFT+PAGE DOWN
    Extend the selection up one page SHIFT+PAGE UP
    Extend the selection to the end of the document CTRL+SHIFT+END
    Extend the selection to the beginning of the document CTRL+SHIFT+HOME
    Select all elements in the document (IDM_TRIED_SELECTALL, DEC MD_SELECTALL) CTRL+A

    Editing

    Description (Command) Key
    Delete the selection or, if there is no selection, the character to the left of the insertion point BACKSPACE
    Delete all of a word to the left of the insertion pointer, not including the space before CTRL+BACKSPACE
    Copy the selection to the Clipboard (IDM_ TRIED_COPY, DECMD_CO PY) CTRL+C
    Paste the contents of the Clipboard to the current location (IDM _TRIED_PASTE, DECMD_P ASTE) CTRL+V
    Cut the selection to the Clipboard (IDM_T RIED_CUT, DECMD_CUT ) CTRL+X
    Delete the selection without placing it on the Clipboard (ID M_TRIED_DELETE, DECMD_ DELETE) DELETE
    Toggle between inserting and overwriting text INSERT
    Undo the most recent formatting commands (IDM_ TRIED_UNDO, DECMD_UN DO) CTRL+Z
    Re-do the most recently undone commands (IDM_ TRIED_REDO, DECMD_RE DO) CTRL+Y
    Find text (IDM_ TRIED_FIND, DECM D_FINDTEXT) CTRL+F
    Display the context menu, if any (equivalent to right-clicking the document) SHIFT+F10
    Display the Hyperlink dialog box (IDM_TRIED_HYPERLINK, DEC MD_HYPERLINK) if the insertion point is within an <A> element CTRL+L in the ActiveX control, CTRL+K in the document object.
    Toggle absolute positioning for the selected element (IDM_TRIED_MAKE_ABSOLUTE, DECMD_MAKE_ABSOLUTE) CTRL+K in the ActiveX control. (No keyboard accelerator for this function exists in the document object.)

    Formatting

    Description (Command) Key
    Toggle bold formatting (IDM_ TRIED_BOLD, DECMD_BO LD) CTRL+B
    Toggle italic formatting (ID M_TRIED_ITALIC, DECMD_ ITALIC) CTRL+I
    Toggle underlining (IDM_TRIED_UNDERLINE, DEC MD_UNDERLINE) CTRL+U
    Increase paragraph indent (ID M_TRIED_INDENT, DECMD_ INDENT) CTRL+T In the ActiveX control. (No keyboard accelerator for this function exists in the document object.)
    Decrease paragraph indent (I DM_TRIED_OUTDENT, DECMD _OUTDENT) CTRL+SHIFT+T in the ActiveX control. (No keyboard accelerator for this function exists in the document object.)

    Usi ng the DHTML Editing Component Document Object

    The Editing Component is an Active Document, so it communicates with its host using the Active Document interfaces. The Editing Component supports the standard Active Document command set and also supports a group of the Editing Component-specific commands that provide access to the Editing Component and MSHTML-specific features.

    The actual parsing and rendering of the HTML documents in the Editing Component is handled by the Mshtml.dll component of Internet Explorer. MSHTML implements an OLE document object that provides support for parsing and rendering with the Dynamic HTML object model, as well as for hosting ActiveX controls and scripts. The Editing Component aggregates MSHTML and is itself an Active Document, so it may be hosted by implementing the Active Document interfaces in your application.

    Note For background information about MSHTML, see the overview provided on the Reusing MSHTML page on the Microsoft MSDN Online Web site.

    The Editing Component exposes all the interfaces provided by MSHTML. A host can control the Editing Component's user interface and context menus using the IDocHostShowUI and IDocHostUIHandler interfaces. Because the Editing Component exposes all MSHTML interfaces, it can be used in place of MSHTML in applications written to use MSHTML by using the Editing Component's GUID at object creation time.

    The DHTML Editing Component exposes only one custom interface: ITriEditDocument. This interface contains methods that allow the HTML source to be managed so the document can be properly rendered on the editing surface. For more details, see Filtering HTML Source.

    The following topics provide details about using the DHTML Editing Component document object:

    See Also

    Overview of the DHTML Editing Component, Using the DHTML Editing Control

    Sending and Receiving Commands

    As part of the Active Document interfaces, both the Editing Component and the host each implement the IOleCommandTar get interface. Through this interface the Editing Component supports the standard Active Document command set and also supports a group of the Editing Component-specific commands that provide access to the Editing Component and MSHTML-specific features.

    Hosts use the IOleCommandTarget::QueryStatus() method to determine if a given command is appropriate for the state of the current document or selection, and the IOleCommandTarget::Exec() method to send a command to the Editing Component. The Editing Component calls the host's implementation of IOleCommandTarget to communicate the following details to the hosting frame:

    Querying Status

    To determine whether a specific command is appropriate for the selection or for the location of the insertion point, you call the QueryStatus method. The syntax is:

    HRESULT QueryStatus( const GUID* pguidCmdGroup, ULONG cCmds,
    OLECMD* prgCmds, OLECMDTEXT* pCmdText)

    When calling this method for the DHTML Editing Component, you specify parameter values as follows:

    pguidCmdGroup Always pass &GUID_TriEditCommandGroup.
    cCmds Number of commands in the prgCmds array.
    prgCmds An array of OLECMD structures with the two members: cmdID and cmdf. The cmdID parameter takes one of the commands listed in Doc Object API Reference. The cmdf member contains An OLECMDF enumeration indicating the status of the command. When calling the method, pass zero in this member. The method then fills this enumeration with status information. Constants for the cmdf enumeration are defined in the DOCOBJ.H file that comes with Visual C++. They are:
    • OLECMDF_SUPPORTED The command is supported for the selection or insertion point.
    • OLECMDF_ENABLED The command is available and enabled.
    • OLECMDF_LATCHED The command is an on-off toggle and is currently on. For example, this value is set if you query the status of the IDM_TRIED_BOLD command against a selection that is already bold.
    • OLECMDF_NINCHED The selection includes a mixture of elements, some that do and some that do not reflect the effect of command and some that do not. For example, this value is returned for the IDM_TRIED_BOLD command if the selection contains some text that is bold and some that is not.

    If the command is not supported, the cmdf member returns zero.

    In general, to simply determine whether a command is available, you can test for the OLECMDF_ENABLED setting. The OLECMDF_LATCHED and OLECMDF_NINCHED settings enable you to set multi-state UI elements, such as buttons that can appear normal, pushed (if the status is latched), or in a "mixed-state" representation (if the status is ninched). A similar set of values is supported for the DHTML Editing control. For details, see Cr eating Toolbars and Menus for the DHTML Editing Control.

    The following shows a sample of how to call the QueryStatus method:

    HRESULT hr = S_OK;
    OLECMD olecmd;
    olecmd.cmdID = IDM_TRIED_BOLD;
    olecmd.cmdf = 0;
    
    hr = pCmdTarget->QueryStatus(&GUID_TriEditCommandGroup,
      1,
      &olecmd,
      NULL);
    
    if( olecmd.cmdf & OLECMDF_ENABLED) != 0 ) {
     // Proceed with call to Exec method
    }
    
    

    Executing Commands

    To execute a command, you call the Exec method. The syntax is:

    HRESULT Exec(const GUID* pguidCmdGroup, DWORD nCmdID,
    DWORD nCmdExecOpt, VARIANTARG* pVarIn, VARIANTARG* pVarOut);

    When calling this method for the DHTML Editing Component, you specify parameter values as follows.

    pguidCmdGroup Always pass &GUID_TriEditCommandGroup.
    nCmdID One of the commands listed in Doc Object API Reference.
    nCmdExecOpt An option specifying whether the command should display a dialog box when being executed. Most commands do not support a user interface. Options are:
    • OLECMDEXECOPT_DODEFAULT Specifies the command's default behavior. Typically, if the command supports a user interface, passing this value causes the dialog box to be displayed. For commands that don't support a user interface, this value should be passed as the default.
    • OLECMDEXECOPT_PROMPTUSER Specifies that a dialog box should be displayed if the command supports one.
    • OLECMDEXECOPT_DONTPROMPTUSER No dialog box should be displayed, even if the commands supports one.
    • pVarIn
    • An additional value passed to the command, if required. Most commands do not required additional values; in those cases, this parameter is passed as NULL.
    • pVarOut
    • A value returned by the command, if any. Most commands do not return values; in those cases, this parameter is passed as NULL.
    Note The documentation for individual commands indicates possible values for the pVarIn and pVarOut parameter, if any.

    For example, here is an example of calling the Exec method with the IDM_TRIED_BOLD command:

    HRESULT hr = S_OK;
    hr = pCommandTarget->Exec(&GUID_TriEditCommandGroup,
      IDM_TRIED_BOLD,
      OCMDEXECOPT_DONTPROMPTUSER,
      NULL,
      NULL);
    }
    
    

    The IDM_TRIED_BOLD command does not support a user interface, so the third parameter is passed as OLECMDEXECOPT_DODEFAULT. Because the IDM_TRIED_BOLD command requires no further information, the last two parameters are passed as NULL.

    For another example of calling the Exec method, see Mo difying Documents Using the IOleCommandTarget Interface.

    For more information on IOleCommandTarget, see MSHTML Editing on the Microsoft MSDN Online Web site.

    Modifying Documents Using the IOleCommandTarget Interface

    The DHTML Editing Component's IOleCommandTar get Non-MSDN Online linkinterface supports two command sets, MSHTML's CMDSETID_Forms3 command set and the Editing Component's GUID_TriEditCommandGroup command set. The CMDSETID_Forms3 command set provides command IDs for most of the Editing Component's basic edit functionality such as text and paragraph formatting. The GUID_TriEditCommandGroup command set provides command IDs for editing absolutely positioned elements; inserting and manipulating HTML tables; and ActiveX control and Java applet UI activation. For a list of command IDs supported by the Editing Component, see Document Object Commands.

    Note For information about another way to edit the document, see Mo difying Documents Using the DHTML Document Object Model.

    Both command sets generally operate on the selection or current insertion point. The following code fragment uses the IDM_TRIED_BOLD command from the CMDSETID_Forms3 command set to format the selected text as bold. The IDM_TRIED_BOLD tag applies the <STRONG> tag to the underlying HTML stream.

    {
     HRESULT hr = S_OK;
     IUnknown* lpUnk = NULL;
     LPOLECOMMANDTARGET pCommandTarget = NULL;
    
     lpUnk = m_pSite->GetObjectUnknown();
     hr = lpUnk->QueryInterface(IID_IOleCommandTarget,
      (void**) &pCommandTarget);
    
     if ( SUCCEEDED(hr) && pCommandTarget != NULL )
     {
      HRESULT hr = S_OK;
    
      // Use the GUID_TriEditCommandGroup command with IDM_TRIED_BOLD
      hr = pCommandTarget->Exec(&GUID_TriEditCommandGroup,
          IDM_TRIED_BOLD,
          MSOCMDEXECOPT_DONTPROMPTUSER,
          NULL,
          NULL);
      pCommandTarget->Release();
    }
    
    return hr;
    }
    
    

    Some commands take an argument as input and some commands return an argument that indicates the state of the selection or document. The following example uses the IDM_TRIED_FONTNAME command to query the Editing Component for the font of the selection.

    Note The Editing Component's GUID_TriEditCommandGroup command set will delegate unknown commands to the CMDSETID_Forms3 command set.
    {
     HRESULT hr = S_OK;
     IUnknown* lpUnk = NULL;
     LPOLECOMMANDTARGET pCommandTarget = NULL;
    
     lpUnk = m_pSite->GetObjectUnknown();
     hr = lpUnk->QueryInterface(IID_IOleCommandTarget,
      (void**) &pCommandTarget);
    
     if ( SUCCEEDED(hr) && pCommandTarget != NULL )
     {
      Variant vOutParam;
      VariantInit(&vOutParam);
    
      // Use the GUID_TriEditCommandGroup command with IDM_FONTNAME
      hr = pCommandTarget->Exec(&GUID_TriEditCommandGroup,
         IDM_TRIED_FONTNAME,
         MSOCMDEXECOPT_DONTPROMPTUSER,
         NULL,
         &vOutParam);
      if (SUCCEEDED(hr))
       {
        _bstr_t fontName;
        _ASSERTE(V_VT(&vOutParam) == VT_BSTR);
        fontName = V_BSTR(&vOutParam);
        pCommandTarget->Release();
       }
      // deallocate the BSTR returned in vOutParam
      VariantClear(&vOutParam);
     }
     return hr;
    }
    
    

    Modifying Documents Using the DHTML Document Object Model

    Another way to manipulate an HTML document is to use the Dynamic HTML object model. This is the same object model that is available on Internet Explorer for performing Dynamic HTML operations on a document. It is available for use in Edit mode in the Editing Component.

    Note For information about using the IOleCommandTarget interface to edit the document, see Mo difying Documents Using the IOleCommandTarget Interface.

    All elements on a page of HTML are exposed through the DHTML Object Model and can be manipulated through their specific interfaces. Also, HTML can be inserted directly into the underlying HTML text stream using TextRanges and the IHTMLElement interfaces's innerHTML and outerHTML properties on document elements. The host can query the Editing Component for the IHMLTDocument2 interface and drill down to a given element in a document to perform a specific operation. An example would be inserting a script block into the document using the document's IHTMLElement::insertAdjacent() method on the <BODY> element.

    For more information on how to use the DHTML object model see the DHTML, HTML, and CSS page of the Microsoft MSDN Online Web Workshop Web site.

    Filtering HTML Source

    Documents can contain elements that require special handling in the DHTML Editing Component in order to be rendered correctly on the editing surface. These include design-time controls, server script (script in ASP pages), and HTML source that is formatted with white space and line breaks.

    Generally speaking, these elements must be modified from their original versions in the source document before being displayed. They remain editable in their modified versions. When the document is saved, the original version of these elements must be restored. If necessary, the original version must also be modified to reflect editing changes made by the user.

    Modifications are made by filtering the document's source stream. A "filter in" operation performs the modifications that make the document suitable for display. A "filter out" operation reverses the modifications and updates the original as required. Filtering affects the following elements as described:

    The following limitations apply to source code formatting retention:

    Applying Filters

    Filtering is performed by calling methods of the ITriEditDocument interface: ITriEditDocument::FilterIn and ITriEditDocument::FilterOut. These methods are used together before loading a document and after saving a document, respectively.

    After an editing session in which the document has been persisted using IPersistStreamInit::Save(), a host can then perform the outbound filtering operation using ITriEditDocument::FilterOut and return the resulting HTML Stream to memory using GetHGlobalFromStream().The host should call IStream::Stat to determine the size of the HTML stream instead of using GlobalSize(), and then write the HTML file with that size.

    Using the DHTML Editing Control

    The DHTML Editing Component ActiveX Control enables Microsoft® Visual Basic®, Web and C++ applications to easily add WYSIWYG editing of DHTML files. It is analogous to the Rich Text Edit control, except it is for DHTML files instead of RTF files.

    The design approach of the DHTML Editing control is to expose existing editing functionality to the script and Web authors. It does not add any editing functionality itself.

    The editing control is provided in both a safe- and unsafe-for-scripting version; both are in the same .ocx file. The unsafe-for-scripting version allows the script author to write to arbitrary locations on the user's file system. This control is meant to be used for intranet applications, not on the public Internet when used on a Web page. The safe-for-scripting version does not allow access to the user's system, which does not allow you to load, save, or print documents.

    The following topics provide details about using the DHTML Editing control:

    See Also

    Overview of the DHTML Editing Component, Using the DHTML Editing Component Document Object

    Hosting the DHTML Editing Component as an ActiveX Control

    The Editing Component can easily be hosted as an ActiveX control from within applications or from Web pages. Internet Explorer 5 includes both versions of the control, including the safe-for-scripting version and the unmarked version. In many environments, such as Microsoft® Visual InterDev™ and Microsoft® Visual Basic®, the DHTML Editing controls are either automatically available on the toolbar or can be added to it as ActiveX controls.

    You can create instances of the control programmatically as well. The program ID (progID) for the safe-for-scripting control is:

    DHTMLSafe.DHTMLSafe
    
    

    Its class ID is:

    2D360201-FFF5-11D1-8D03-00A0C959BC0A
    
    

    The progID for the version of the control not marked safe for scripting is:

    DHTMLEdit.DHTMLEdit
    
    

    Its class ID is:

    2D360200-FFF5-11D1-8D03-00A0C959BC0A
    
    

    For example, to create an instance of the safe-for-scripting version of the control on a Web page, create an <OBJECT> element like this:

    <OBJECT
    classid="clsid:2D360201-FFF5-11d1-8D03-00A0C959BC0A"
            ID=DHTMLSafe1
            HEIGHT=400 WIDTH=500
    </OBJECT>
    
    

    For more information, see Deploying Applications that Use the DHTML Editing Component.

    Loading and Saving Documents

    The DHTML Editing control provides a variety of means by which you can load documents for editing and save them:

    The DHTML Editing control supports two methods that work directly against files on disk: LoadDo cument and SaveDo cument. Both of these methods simply take paths and file names as parameters and then handle the lower-level jobs of opening and closing files as needed. Both also support an option that allows you to display standard Windows dialog boxes (Open and Save As) to find documents or directories.

    Note The version of the DHTML Editing control marked as safe for scripting does not support either of these methods.

    By calling the LoadURL method, your application can read a document from any arbitrary Internet location that the user has access to. The LoadURL method supports all standard Internet protocols, including HTTP, FTP, Gopher, and so on, including File.

    NoteThe version of the DHTML Editing control marked as safe for scripting supports only the HTTP and FTP protocols, and it can load documents only from the same domain as the hosting Web page. Attempting to load documents using another protocol or from another domain results in an error. Furthermore, the safe-for-scripting control does not support server redirection of URLs.

    There is no corresponding universal mechanism for writing data to a Web server, so your application must provide its own implementation for doing this. For example, your application might use HTTP Post to transmit the document to the Web server. See the WebApp sample for an example of this. For more details about sample applications, see "Sample Applications" under Overview of the DHTML Editing Component.

    Note The WebApp sample does not address user authentication and access permission; these issues will need to be addressed in a production application.

    Some applications do not store documents as files. For example, they might be stored in a database or might require custom server logic to be read and written. In these types of applications, you need to be able to load and save a document as a text string. This facility is provided via the Docume ntHTML property, which contains a string representing the document as an HTML document. The DocumentHTML property contains not only the <BODY> portion of the document that the user can edit directly, but the HEAD portion as well, and all the tags required to make the document well-formed, such as <HTML> and </HTML>. The property is read/write; any change made to the string in DocumentHTML is made immediately in the control and vice versa.

    A typical scenario is an application that stores documents in a database. The application can use database access commands to read a string out of the database containing the HTML document. The application can then set the DocumentHTML property to this string and allow the user to edit the document in the control. When the user saves the document, the application can get the contents of the DocumentHTML property and write it as a string back to the database.

    A Web-based application might follow a similar strategy. The document could be loaded either by downloading a string from the Web, or more directly using the LoadURL method. When the user saves the document, the contents of the DocumentHTML property can be submitted to the server, where a server-based process can then write the string to a file or to a database, as appropriate.

    You can also read and write portions of the document as a string using the DOM property. For example, you can use the following command to return the entire contents of a document's <BODY> element:

    txtBody = DOM.body.innerHTML
    
    Note If you are accessing the document using the DOM property, use the Fi lterSourceCode method to remove tags temporarily inserted into the document by the DHTM Editing Component.

    See Also

    Working with HTML Source Code

    Modi fying Documents in the DHTML Editing Control

    The document displayed in the DHTML Editing control can be modified in a number of ways:

    Creating Toolbars and Menus for the DHTML Editing Control

    By default, the DHTML Editing control does not support toolbars, menus, or other user interface to help users edit the document. These are provided by the host application.

    The specific means by which you create a toolbar or menu depends on the host environment. For example, Visual Basic includes tools to add menus to a form. Toolbars can be created using small additional forms.

    However, no matter how you create the user interface for a toolbar or menu, the basic functionality is the same. For both, you must:

    You can see toolbars and menus in action in the Visual Basic VBEdit sample application and in the Web Fulledit.htm sample application. For more details about sample applications, see "Sample Applications" under Overview of the DHTML Editing Component.

    Binding Toolbars and Menus to Editing Functionality

    A toolbar button or menu command will either call a control method, set a control property, or (most frequently) execute a formatting command.

    For example, you might use a menu command called Open to load a new document into the control. In Visual Basic, you can create a menu with the Open command on it, and then write a handler for the Open command's Click event that looks like this:

    Private Sub mnuOpen_Click()
        DHTMLEdit.LoadURL "", True
    End Sub
    

    Similarly, a toolbar button called btnToggleGrid can set the SnapToGr id property to toggle the grid:

    Private Sub btnToggleGrid_Click()
        DHTMLEdit1.SnapToGrid = Not(DHTMLEdit1.SnapToGrid)
    End Sub
    

    Most editing and formatting commands are implemented by calling the ExecCom mand method. This method takes a numeric command ID, which is usually passed as a constant such as DECMD_BOLD, and typically operates on the selection. For example, the following shows how you can call ExecCommand to toggle bold formatting for the selection:

    Private Sub btnToggleBold_Click()
        DHTMLEdit1.ExecCommand DECMD_BOLD
    End Sub
    

    Before executing a command, it is usually a good idea to determine if the command is valid in the current context. For example, if the user has selected an image, the DECMD_BOLD command will not work. To test a command, call the QuerySt atus method, which returns a status code indicating one of several possible status values. The following example shows the same handler as before to toggle bold formatting, but adds a test with QueryStatus:

    Private Sub btnToggleBold_Click()
         If QueryStatus(DECMD_BOLD) = DECMDF_ENABLED Then
            DHTMLEdit1.ExecCommand DECMD_BOLD
        End If
    End Sub
    

    Enabling and Disabling Toolbars and Menus

    You can make your toolbars and menus more sophisticated by conditionally enabling and disabling their individual elements. To determine whether a toolbar button or a menu command should be enabled or disabled, you again call the QuerySt atus method.

    Because the availability of various commands depends on the current editing state, you call the QueryStatus method in a handler for the Disp layChanged event. This event is fired whenever the user makes any change whatsoever in the document, including simply moving the insertion point.

    The following simple Visual Basic example shows one way to use DisplayChanged to update the user interface.

    Private Sub DHTMLEdit1_DisplayChanged()
        If DHTMLEdit1.QueryStatus(DECMD_BOLD) = DECMDF_ENABLED Then
            btnBold.Enabled = True
        Else
            btnBold.Enabled = False
        End If
    
        If DHTMLEdit1.QueryStatus(DECMD_ITALIC) = DECMDF_ENABLED Then
            btnItalic.Enabled = True
        Else
            btnItalic.Enabled = False
        End If
    End Sub
    

    This example is verbose--you would more likely enable and disable buttons as a group in a toolbar--but illustrates the basic principle.

    QueryStatus can actually return a number of different values. In addition to DECMDF_ENABLED and DECMDF_DISABLED, commands can be reported as:

    By testing for these extra values (particularly DECMD_LATCHED; DECMDF_NINCHED is not used very much), you can create multi-state toolbar or menu items. For example, the Visual Basic Toolbar control supports not just enabled and disabled states for individual buttons, but also a "pressed" state (tbrPressed) that can be used to represent a status of DECMDF_LATCHED. Similarly, the DECMDF_NINCHED state can be used to set the MixedState property of a Visual Basic Toolbar control.

    For an example of using DECMDF_LATCHED, see the VBEdit sample application. For more details about sample applications, see "Sample Applications" under Overview of the DHTML Editing Component.

    Working with HTML Source Code

    The DHTML Editing control displays a document in a near-WYSIWYG way, but displays only the <BODY> portion of the document.

    You can also work with the raw HTML view of the document, either read/write or read-only. The control's DocumentHTML property contains the full HTML text of the document, including the <HEAD> section. You can load the text returned by this property into a separate editing control.

    For example, the following code creates a new HTML document dynamically and loads it into the control:

    head =
    "<HTML><HEAD><TITLE></TITLE></HEAD&g
    t;"
    body = "<BODY><H1>Heading!</H1>This is a new
    document."
    finish = "</BODY></HTML>"
    DHTMLEdit1.DocumentHTML = head & body & finish
    
    

    If you load the HTML of the document into an editable control, users can change the HTML directly. You can then write the text back to the DocumentHTML property. Doing so starts the document load process to parse the HTML and redisplay the document contents.

    While a document is being loaded (or reloaded), the Busy property is true. When the control has finished parsing and loading the document, the DocumentComplete event is fired and the Busy property is set to false. When getting the value of the DocumentHTML property, you must be sure that the document in the DHTML Editing control has finished loading, otherwise an error results when you try to get the value of the property.

    The following Visual Basic example illustrates how you might use the DocumentHTML property. The HTML text is displayed in an editable text box called txtHTML. The text box is initially loaded when the DocumentComplete event is fired. The text in the txtHTML control is kept up to date by reloading it whenever the DisplayChanged event is fired. To be safe, this update is made only if the control is not in a busy state. Finally, changes to the raw HTML made in the txtHTML control are copied back to the document when the user presses a button called btnSaveHTML.

    ' Fired when the document has been initialized and it is safe
    ' to get the DocumentHTML property.
    Private Sub DHTMLEdit1.DocumentComplete()
        txtHTML.Text = DHTMLEdit1.DocumentHTML
    End Sub
    
    ' Fired each time the document is touched. In this routine it
    ' is important to make sure the document has been initialized
    ' before trying to get the DocumentHTML property.
    Private Sub DHTMLEdit1.DisplayChanged()
        On Error Resume Next
        If DHTMLEdit1.Busy = False Then
            txtHTML.Text = DHTMLEdit1.DocumentHTML
        End If
    End Sub
    
    ' Copies HTML changes from the text control back to the
    ' document.
    Private Sub btnSaveHTML_Click()
        DHTMLEdit1.DocumentHTML = txtHTML.Text
    End Sub
    
    

    Accessing the DHTML Document Object Model

    Scripts running in the document displayed by the DHTML Editing control have access to the document's DHTML document object model (DOM) in order to manipulate the contents of the document dynamically. The host application can get access to the same HTML DOM, which provides extremely fine-grained, powerful programmatic access to the contents of the document.

    Note You can also use the DHTML document object model to receive DHTML events in the host application. For details, see Responding to DHTML Editing Control Events.

    The control's DOM property exposes an object that the host can use in place of the DHTML document object. This top-level object then provides access to the entire hierarchy of the document. Using the DOM property, you can perform functions such as:

    Each of these functions is discussed in more detail below as examples of how to use the DOM property.

    Note You should not use the value of the DOM property when calling the DHTML Editing control's methods or setting its properties. For example, you should not use a value returned via the DOM property as a parameter for the LoadURL method. Doing so can cause unexpected results.

    Working with the Selection

    The selection is accessed through the DHTML selection object. The selection object in turn has a type property that returns a value of None, Text, or Control.

    If the type is Text, you can call the selection object's createRange method to obtain a TextRange object corresponding to the selection. The text can then be accessed through the TextRange object's text</ a> and html Text properties.

    The following JavaScript function demonstrates this:

    function ShowSelection(){
       sel = DHTMLEdit.DOM.selection;
       if ( "Text" == sel.type ){
          range = sel.createRange();
          alert( range.htmlText );
       }
       else
          alert( "No text selected" );
    }
    
    

    To identify the selection the mouse is pointing to, you use the same objects, ultimately getting the outerHTML property of the parent.

    The following Visual Basic code illustrates how to do this. The code tests the selection object's type. If the type is Text, the routine reduces (collapses) the selection to the current insertion point. (If you did not want to change the selection, you could duplicate the range and then collapse the copy.)

    Private Sub GetElementUnderInsertionPoint()
       Dim rg As IHTMLTxtRange
       Dim ctlRg As IHTMLControlRange
       Select Case DHTMLEdit1.DOM.selection.Type
          Case "None", "Text"
             ' This reduces the selection to just the insertion
             ' point. The parentElement method will then return the
             ' element directly under the mouse pointer.
             Set rg = DHTMLEdit1.DOM.selection.createRange
             rg.collapse
             MsgBox rg.parentElement.outerHTML
          Case "Control"
             ' A form or image is selected. The commonParentElement
             ' will return the site selected element.
             Set ctlRg = DHTMLEdit1.DOM.selection.createRange
             MsgBox ctlRg.commonParentElement.outerHTML
       End Select
    End Sub
    
    

    Dynamically Moving the Insertion Point

    You can set the location of the insertion point programmatically using TextRanges. The following Visual Basic code demonstrates how to set the insertion point at the end of the document:

    Private Sub MoveToEnd()
        Dim range As IHTMLTxtRange
        Set range = DHTMLEdit1.DOM.body.createTextRange()
        range.collapse False
        range.Select
    End Sub
    
    

    Responding to DHTML Editing Control Events

    The DHTML Editing control supports a small set of events that are fired to indicate a change in state or a user gesture in the document. The host application can handle these events like any other events.

    Two events in particular are useful for managing the editing environment:

    You can use the DisplayChanged event to update any toolbars or menus that you display for the control. Typically, each time DisplayChanged is fired, you make a succession of calls to the QueryStatus method to determine if certain editing facilities should be enabled or disabled. For an example, see the VBEdit sample application. For more details about sample applications, see "Sample Applications" under Overview of the DHTML Editing Component.

    Note The DisplayChanged event is fired very frequently (with each user gesture), so if you write a handler for this event, the handler should be as efficient as possible, or it will adversely affect performance in the control.

    The DocumentComplete event tells the host application that the document in the control is ready to be manipulated. When you load a new document or change the document's text (for example, by setting the DocumentHTML property), the control parses the document and rebuilds the document's object model. This process occurs asynchronously, so that you can continue to work with the control. When the parsing has been finished, the control fires the DocumentComplete event to alert you that the document is ready. If you attempt to access the document directly (using the DocumentHTML or DOM properties) before this event fires, an error will occur. (You can also test the Busy property to determine if the document is ready.)

    A typical use for the DocumentComplete event is to to initialize and enable toolbars and menus.

    Handling DHTML Events Inside the Document

    The document inside a DHTML Editing control receives DHTML object model events, which can be used to run scripts inside the document (when the control is in Browse mode). The host application can receive a specific set of DHTML events as well.

    For example, when a user clicks the document in the control, the onclick event is generated. The host application receives an onclick event, even if the object model for the host application normally uses a different name for the event.

    Note For a list of events available in the DHTML object model, see the DHTML Events page on the Microsoft MSDN Online Web Workshop Web site.

    The host application can receive the following DHTML events. The links in the list below take you to the Microsoft MSDN Online Web site, where each event is documented in detail.

    Note If you are hosting the DHTML Editing control in a Web page, be aware that events originating in the control are not bubbled through the hosting Web page's document object hierarchy. For example, if the DHTML Editing control fires an onclick event, you can capture that event in the hosting Web page using a handler such as DHTMLEdit1_onclick. However, you could not capture the event using a higher-level handler such as window_onclick.

    DHTML object model events are sent without parameters. Within the object model, event information is available instead in the event< /a> object.

    The DHTML event object is not directly available to the host application. However, a host application can access it indirectly using the DOM property to get access to the DHTML object model. Then within that model, the host application can use the parentWindow property and the event object. In the host application, the event object is created with the object type IHTMLEventObj.

    The following shows a handler in Visual Basic for a DHTML Editing control onclick event. The code illustrates how you can use the host's version of the event object to get information about the event and display it in a text box.

    Private Sub DHTMLEdit1_onclick()
        Dim e As IHTMLEventObj
        Set e = DHTMLEdit1.DOM.parentWindow.event
        txtLocation.Text = e.X & ", " & e.Y
    End Sub
    
    

    For more examples of how to receive DHTML events in the host, see the VBDom sample application. For more details about sample applications, see "Sample Applications" under Overview of the DHTML Editing Component.

    Handling Errors in the DHTML Editing Control

    The methods supported by the DHTML Editing control can report errors. For example, the LoadDocument method raises an error if a bad path or file name is passed to it.

    You can capture these errors using the standard error-handling facilities of your host environment. For example, if you are working in C, error values are returned as return values by the method call. In Visual Basic and VBScript, error handling is managed by the On Error statement and the Err object.

    The level of detail you can derive from an error condition depends on what your host application is. For example, in Visual Basic, VBScript, C and C++, you can check for specific errors by number. In JScript, you can test for an error and, if one is detected, get the text of the error message.

    Error numbers are defined as constants in various include files that are part of the DHTML Editing Component samples. For example, the Dhtmled.h file includes constants usable in C, and the Dhtmled.vbs file contains constants defined for use with Visual Basic and VBScript. For more details about include files, see "Include and Header Files" under Requirements.

    Note The documentation for each method indicates the error values it can return.

    The sections below provide information about handling errors in VB, VBScript, and JScript.

    Trapping Errors in Visual Basic and VBScript

    In Visual Basic or VBScript, you use the On Error statement to trap errors. If you do not include this statement in your code, error conditions pass through to the control and can result in fatal errors.

    Note In Visual Basic and VBScript, the error code indicating success (S_OK) cannot be trapped. Successful completion is implicit if an error is not trapped.

    Using Error Constant Values

    Error values are defined as constants in the file Dhtmled.vbs. In VBScript, you can include this file using syntax such as the following:

    <SCRIPT LANGUAGE="VBScript"
    SRC="\VBEdit\INC\DHTMLEd.vbs"></SCRIPT>
    
    

    In Visual Basic, you cannot directly include this file in your project. However, you can make the error constants available by creating a module that defines those constants. You can do this easily by copying the constant definitions from the Dhtmled.vbs file to the module, which might then look as follows:

    ' Defined in a module
    Public Enum General
        DE_E_INVALIDARG = &h5
        DE_E_ACCESS_DENIED = &h46
        DE_E_PATH_NOT_FOUND = &h80070003
        DE_E_FILE_NOT_FOUND = &h80070002
        DE_E_UNEXPECTED = &h8000ffff
        DE_E_DISK_FULL = &h80070027
        DE_E_NOTSUPPORTED = &h80040100
        DE_E_FILTER_FRAMESET = &h80100001
        DE_E_FILTER_SERVERSCRIPT = &h80100002
        DE_E_FILTER_MULTIPLETAGS = &h80100004
        DE_E_FILTER_SCRIPTLISTING = &h80100008
        DE_E_FILTER_SCRIPTLABEL = &h80100010
        DE_E_FILTER_SCRIPTTEXTAREA = &h80100020
        DE_E_FILTER_SCRIPTSELECT = &h80100040
        DE_E_URL_SYNTAX = &h800401E4
        DE_E_INVALID_URL = &h800C0002
        DE_E_NO_SESSION = &h800C0003
        DE_E_CANNOT_CONNECT = &h800C0004
        DE_E_RESOURCE_NOT_FOUND = &h800C0005
        DE_E_OBJECT_NOT_FOUND = &h800C0006
        DE_E_DATA_NOT_AVAILABLE = &h800C0007
        DE_E_DOWNLOAD_FAILURE = &h800C0008
        DE_E_AUTHENTICATION_REQUIRED = &h800C0009
        DE_E_NO_VALID_MEDIA = &h800C000A
        DE_E_CONNECTION_TIMEOUT = &h800C000B
        DE_E_INVALID_REQUEST = &h800C000C
        DE_E_UNKNOWN_PROTOCOL = &h800C000D
        DE_E_SECURITY_PROBLEM = &h800C000E
        DE_E_CANNOT_LOAD_DATA = &h800C000F
        DE_E_CANNOT_INSTANTIATE_OBJECT = &h800C0010
        DE_E_REDIRECT_FAILED = &h800C0014
        DE_E_REDIRECT_TO_DIR = &h800C0015
        DE_E_CANNOT_LOCK_REQUEST = &h8
    End Enum
    
    

    Responding to Errors

    If an error occurs, you get error information from the Err object. The following shows an example of how to trap errors that can occur when the LoadDocument method is called in response to a button click. The actual error-handling routine is written as a separate subroutine.

    Private Sub btnLoadDocument_Click()
        On Error GoTo CatchErr:
        DHTMLEd1.LoadDocument( txtFileName.Text )
        Exit Sub
    CatchErr:
        errNum = Err.Number    ' Get error information from Err object
        DisplayError "LoadDocument", errNum
    End Sub
    
    Private Sub DisplayError(CommandName, errNum)
        Select Case errNum
        Case DE_E_PATH_NOT_FOUND
            MsgBox "An invalid path was specified."
        Case DE_E_FILE_NOT_FOUND
            MsgBox "An invalid file name was specified."
        Case DE_E_ACCESSS_DENIED
            MsgBox "Access to the file was denied."
        Case Else
            MsgBox "Error " & errNum & " occured
    when executing " & _
                   CommandName
        End Select
    End Sub
    
    

    In VBScript, you can write similar code. You cannot branch on an error condition, so you must test for an error explicitly after calling the method.

    Function btnLoadDocument_onclick()
      On Error Resume Next
      DHTMLEdit1.LoadDocument "c:\MyFiles\Test.htm"
      errNum = err.Number
      If err.Number then
         DisplayError(errNum)
      End if
    End Function
    
    Sub DisplayError(errNum)
        Select Case errNum
          Case DE_E_PATH_NOT_FOUND
            MsgBox "Invalid path."
          Case DE_E_FILE_NOT_FOUND
            MsgBox "File not found."
          Case Else
            MsgBox "Error " & errNum & " when
    trying to load file."
        End Select
    End Sub
    
    

    Trapping Errors in JScript

    JScript does not have direct access to an error object or other structure. However, when using JScript in Internet Explorer, you can bind an error-handling function to an error event using the window object's onerror event.

    The error-handling function you specify receives three parameters: the text of an error message, the URL of the Web page, and the line where the error occurred. The error-handling function should return true to suppress the default Internet Explorer error.

    Note For error trapping to work for JScript in Internet Explorer, the script debugger must be disabled.

    The following shows a simple error-handling scenario in JScript. The script includes a button onclick handler that calls the DHTML Editing control's LoadDocument method, passing it a path and file name.

    Tip A very common error in JScript is to forget to double the backslash characters (\) used in path names. Single backslashes are interpreted as escape characters.
    <SCRIPT LANGUAGE="JavaScript">
    onerror=displayError;   // Binds error event to
    "displayError" routine
    
    function btnLoadDocument_onclick(){
       // Loads a document into the DHTML Editing control
       // Note doubled backslashes in path name
       DHTMLEdit1.LoadDocument("c:\\MyDocs\\Test.htm");
    }
    
    function displayError(msg, url, line){
       // Error handling routine
       alert("The following error occured:\n\n" + msg);
       return true;  // Suppresses Internet Explorer error
    }
    </SCRIPT>
    
    

    Glossary

    absolute positioning

    A CSS feature that allows elements in a Web page to be positioned using style attributes that function like x and y coordinates. Using CSS styles, absolutely positioned elements also support a z-index that allows them to appear in front of or behind other elements on the page. Absolute positioning is a DHTML feature implemented through various style attributes. See also Working with Absolutely Positioned Elements.

    Active Server Page (ASP), .asp file

    A Web page that includes server script to be executed by Microsoft® Internet Information Server (IIS). The .asp extension on the file alerts the server that it should process the file before sending it to the browser. After the server script in an .asp file has been processed by the server, the file is sent to the browser, in the same manner as an .htm file.

    Browse mode

    A view of the document similar to the way it will appear in Internet Explorer. In Browse mode, scripts, links, and marquees are live. Compare Edit mode. See also Editing and Browsing Documents.

    design-time control (DTC)

    An ActiveX control that generates HTML text and script. DTCs present a graphical interface and support property pages at design time, similar to any other control. They then generate HTML text and script that implements their functionality at run time.

    directly selectable elements

    Elements that can be individually selected for editing, including images, tables, controls, absolutely positioned elements, and so on. Text is not directly selectable, because you must select one or more characters before applying attributes to it. See also Selecting Elements.

    Edit mode

    A near-WYSIWYG view of the document that allows the user to add, delete, and modify elements on the page. To help with editing, Edit mode displays some document elements that are invisible when the document is viewed in the browser; some elements are displayed as glyphs. Compare Browse mode. See also Editing and Browsing Documents.

    glyph

    A small graphical character that marks the location of an element that has no visible component. For example, if script appears in the <BODY> portion of a document, and if the control is set to display details (using the IDM_TRIED_SHOWDETAILS command or ShowDetails property), a glyph [cs4Y312 2943 bytes ] appears in the document. Glyphs can help prevent users from inadvertently deleting elements that they do not know are there. See also Displaying Glyphs for Non-Visual Elements.

    safe for scripting, script-safe

    A security setting for a control signifying that the control cannot be used in any way that compromises a user's system, no matter how its properties are set, its methods are called, or its events are handled. In practical terms, this typically means the control cannot read or write to the user's disk or registry, call another object with a higher security rating (such as an applet), or use any memory or system resources outside a browser's control. The DHTML Editing control comes in two versions, one marked safe for scripting and one that is not marked. The safe-for-scripting version is typically used in public Web-based applications. The unmarked version is used in standalone, non-Web-based applications. See also The DHTML Editing Component and Browser Security. For general information about ActiveX safety, see Safe Initialization and Scripting for ActiveX Controls on the Microsoft MSDN Online Web Workshop Web site.

    UI activation

    An editing mode in which the textual content of an element (such as a button caption) can be edited directly, rather than by using a Properties window or other indirect means. UI activation is supported for some directly selectable elements. See also Selecting Elements.


Back to topBack to top

Did you find this material useful? Gripes? Compliments? Suggestions for other articles? Write us!

© 1999 Microsoft Corporation. All rights reserved. Terms of use.