Content Services
The IContentService interface is the primary entry point for programmatically reading, writing, and otherwise manipulating the HTML document hosted by a WinFormHtmlEditor control. Access it through htmlEditor1.Content. Members fall into three groups: bulk content I/O (get/set body, document, files), targeted insertion (HTML at caret, head injection, scripts), and document inspection (element lookup, attribute access, link and image enumeration). Two sub-services are reachable through this interface: TableAuthoringService for table row/column/cell authoring and MailMerge for host-registered placeholder fields.
All methods operate against the currently active document and fire the editor's normal change notifications. Callers should not invoke these methods from non-UI threads. Methods that depend on a live MSHTML document require the editor to be in WYSIWYG design mode; calls made from source-edit mode are either ignored or return last-loaded data depending on the method.
GetBodyText Method
Returns the plain-text content of the document body, with HTML markup stripped. Use this for indexing, comparison, or display in a non-HTML surface.
Syntax
string GetBodyText();Returns
string -- the plain-text body content.
Example
string body = htmlEditor1.Content.GetBodyText();
Console.WriteLine($"Plain body has {body.Length} chars");GetFormattedPlainText Method
Similar to GetBodyText but preserves block-level layout cues such as paragraph line breaks. Try both algorithms and pick the one whose output best matches the host application's expectations.
Syntax
string GetFormattedPlainText();Returns
string -- the formatted plain-text body.
Example
string formatted = htmlEditor1.Content.GetFormattedPlainText();
File.WriteAllText(@"C:\temp\export.txt", formatted);SetBodyText Method
Replaces the document body with the supplied plain text. HTML metacharacters (<, >, &) in the input are escaped automatically.
Syntax
void SetBodyText(string text);Parameters
| Name | Type | Description |
|---|---|---|
| text | string | The plain text to set as the body content. |
Example
htmlEditor1.Content.SetBodyText("Quarterly report draft - 2026 Q1");GetBodyHtml Method
Returns the HTML markup contained in the document body. The getInXhtml parameter controls whether the output is normalized to XHTML (self-closing void tags, lowercase names, quoted attributes).
Syntax
string GetBodyHtml(bool getInXhtml);Parameters
| Name | Type | Description |
|---|---|---|
| getInXhtml | bool | If true, returns XHTML-normalized markup; otherwise the raw MSHTML serialization. |
Returns
string -- the body HTML.
Example
string xhtml = htmlEditor1.Content.GetBodyHtml(getInXhtml: true);
XDocument doc = XDocument.Parse("<root>" + xhtml + "</root>");SetBodyHtml Method
Replaces the document body markup with the supplied HTML. Equivalent to assigning the WinFormHtmlEditor.BodyHtml property.
Syntax
void SetBodyHtml(string bodyHtml);Parameters
| Name | Type | Description |
|---|---|---|
| bodyHtml | string | HTML fragment to place between the body open and close tags. |
Example
htmlEditor1.Content.SetBodyHtml("<h1>Welcome</h1><p>Edit me.</p>");GetDocumentHtml Method
Returns the full HTML document including the DOCTYPE, head, and body. Use this when the host needs the complete file payload for save or upload.
Syntax
string GetDocumentHtml();Returns
string -- the complete document HTML.
Example
string fullDoc = htmlEditor1.Content.GetDocumentHtml();
File.WriteAllText(@"C:\temp\out.html", fullDoc, Encoding.UTF8);SetDocumentHtml Method
Replaces the entire document with the supplied HTML, including DOCTYPE, head, and body. Equivalent to assigning the WinFormHtmlEditor.DocumentHtml property.
Syntax
void SetDocumentHtml(string docHtml);Parameters
| Name | Type | Description |
|---|---|---|
| docHtml | string | The complete HTML document to load. |
Example
string template = File.ReadAllText(@"C:\templates\letter.html");
htmlEditor1.Content.SetDocumentHtml(template);GetDocumentXml Method
Returns the document content serialized as XML. Useful when the host needs to persist or interchange the document through an XML pipeline.
Syntax
string GetDocumentXml();Returns
string -- XML representation of the document.
Example
string xml = htmlEditor1.Content.GetDocumentXml();
XDocument.Parse(xml).Save(@"C:\temp\doc.xml");GetBodyStyleAsDom Method
Returns the body element's style as an mshtml.IHTMLStyle COM pointer. Use this to read or mutate individual CSS properties without parsing the style string. Returns null when no body element is available (e.g. source-edit mode).
Syntax
IHTMLStyle GetBodyStyleAsDom();Returns
mshtml.IHTMLStyle -- the body style DOM wrapper.
Example
IHTMLStyle style = htmlEditor1.Content.GetBodyStyleAsDom();
if (style != null)
{
style.backgroundColor = "#fafafa";
style.color = "#222";
}GetBodyStyle Method
Returns the value of the body element's style attribute as a CSS declaration string.
Syntax
string GetBodyStyle();Returns
string -- the inline CSS string.
Example
string css = htmlEditor1.Content.GetBodyStyle();
Debug.WriteLine($"Body inline CSS = {css}");SetBodyStyle Method
Writes the supplied CSS declaration string to the body element's style attribute, replacing any existing value.
Syntax
void SetBodyStyle(string styleValue);Parameters
| Name | Type | Description |
|---|---|---|
| styleValue | string | CSS declaration list, for example margin:8px; color:#333. |
Example
htmlEditor1.Content.SetBodyStyle("font-family:Segoe UI; padding:12px; color:#222;");GetBodyClassName Method
Returns the body element's class attribute, or empty string when no class is set.
Syntax
string GetBodyClassName();Returns
string -- the body class name.
Example
if (htmlEditor1.Content.GetBodyClassName() != "dark")
htmlEditor1.Content.SetBodyClassName("dark");SetBodyClassName Method
Sets the body element's class attribute. Pair this with an InsertHtmlBetweenHead call that injects the matching <style> block to switch the document's theme at runtime.
Syntax
void SetBodyClassName(string className);Parameters
| Name | Type | Description |
|---|---|---|
| className | string | The CSS class name to attach to <body>. |
Example
htmlEditor1.Content.SetBodyClassName("print-preview");GetAllLinkHrefs Method
Returns the list of href attribute values for every anchor (<a>) in the document body. Use this to validate or rewrite outgoing URLs before publication.
Syntax
string[] GetAllLinkHrefs();Returns
string[] -- array of hyperlink URLs.
Example
foreach (string href in htmlEditor1.Content.GetAllLinkHrefs())
{
if (!Uri.IsWellFormedUriString(href, UriKind.Absolute))
Debug.WriteLine($"Broken link: {href}");
}GetAllImageSources Method
Returns the list of src attribute values for every <img> element in the body, in document order.
Syntax
string[] GetAllImageSources();Returns
string[] -- array of image source URLs.
Example
string[] images = htmlEditor1.Content.GetAllImageSources();
MessageBox.Show($"Document references {images.Length} image(s).");InsertHtml Method
Inserts an HTML fragment at the caret position without disturbing focus. The canonical way to plug arbitrary markup into the document from a custom toolbar button. Script blocks are filtered out by this method; use InsertScript for those.
Syntax
void InsertHtml(string htmlText, bool keepSelected);Parameters
| Name | Type | Description |
|---|---|---|
| htmlText | string | The HTML fragment to insert. |
| keepSelected | bool | If true, the inserted markup remains selected after insertion. |
Example
htmlEditor1.Content.InsertHtml("<p>Hello, <b>world</b></p>", keepSelected: false);InsertText Method
Inserts a plain-text fragment at the caret. HTML metacharacters in the input are escaped (so < becomes <).
Syntax
void InsertText(string text);Parameters
| Name | Type | Description |
|---|---|---|
| text | string | The plain text to insert. |
Example
htmlEditor1.Content.InsertText(DateTime.Now.ToString("yyyy-MM-dd HH:mm"));InsertHorizontalRule Method
Inserts an <hr> horizontal-rule element at the caret position.
Syntax
void InsertHorizontalRule();Example
private void DividerButton_Click(object sender, EventArgs e)
{
htmlEditor1.Content.InsertHorizontalRule();
}InsertScript Method
Inserts a script block at the caret position. InsertHtml strips <script> tags; use this method instead when the script must be preserved in the document.
Syntax
void InsertScript(string scriptMarkUp);Parameters
| Name | Type | Description |
|---|---|---|
| scriptMarkUp | string | The <script>...</script> markup to insert. |
Example
htmlEditor1.Content.InsertScript("<script>console.log('hi');</script>");InsertHtmlBetweenHead Method
Inserts the supplied HTML inside the document's <head> section. Useful for injecting <style>, <link>, <meta>, or <script> elements that should live in the head rather than in the body.
Syntax
void InsertHtmlBetweenHead(string insertingHtml);Parameters
| Name | Type | Description |
|---|---|---|
| insertingHtml | string | The HTML to append into <head>. |
Example
htmlEditor1.Content.InsertHtmlBetweenHead(
"<style id='theme'>body { background:#222; color:#eee; }</style>");RemoveHtmlElementFromHeadByTag Method
Removes every element inside <head> whose tag name matches tagName. Tag matching is case-insensitive.
Syntax
void RemoveHtmlElementFromHeadByTag(string tagName);Parameters
| Name | Type | Description |
|---|---|---|
| tagName | string | HTML tag name, e.g. link or style. |
Example
// Clear all stylesheet links before reapplying a fresh theme.
htmlEditor1.Content.RemoveHtmlElementFromHeadByTag("link");RemoveHtmlElementFromHeadById Method
Removes the element inside <head> whose id attribute matches the supplied value. No-op when no matching element exists.
Syntax
void RemoveHtmlElementFromHeadById(string id);Parameters
| Name | Type | Description |
|---|---|---|
| id | string | Element id attribute. |
Example
htmlEditor1.Content.RemoveHtmlElementFromHeadById("theme");RemoveHtmlElementById Method
Removes the element anywhere in the document whose id attribute matches the supplied value.
Syntax
void RemoveHtmlElementById(string id);Parameters
| Name | Type | Description |
|---|---|---|
| id | string | Element id attribute. |
Example
htmlEditor1.Content.RemoveHtmlElementById("legacyBanner");ChangeElementId Method
Renames the id attribute of the element from oldId to newId. Useful when restructuring a document programmatically.
Syntax
void ChangeElementId(string oldId, string newId);Parameters
| Name | Type | Description |
|---|---|---|
| oldId | string | The existing element id. |
| newId | string | The replacement id. |
Example
htmlEditor1.Content.ChangeElementId("intro", "introduction");ElementExists Method
Returns true if an element with the supplied id exists anywhere in the document.
Syntax
bool ElementExists(string elementId);Parameters
| Name | Type | Description |
|---|---|---|
| elementId | string | Element id to test. |
Returns
bool -- true if found.
Example
if (!htmlEditor1.Content.ElementExists("footer"))
htmlEditor1.Content.InsertHtml("<div id='footer'>(c) 2026</div>", false);GetAttributeValueOfAnElement Method
Returns the value of the named attribute on the element with the given id.
Syntax
string GetAttributeValueOfAnElement(string elementId, string attributeName);Parameters
| Name | Type | Description |
|---|---|---|
| elementId | string | Element id. |
| attributeName | string | Attribute name (e.g. href). |
Returns
string -- attribute value, or empty string when not set.
Example
string href = htmlEditor1.Content.GetAttributeValueOfAnElement("mainLink", "href");SetAttributeValueOfAnElement Method
Sets the value of the named attribute on the element with the given id.
Syntax
void SetAttributeValueOfAnElement(string elementId, string attributeName, string value);Parameters
| Name | Type | Description |
|---|---|---|
| elementId | string | Element id. |
| attributeName | string | Attribute name. |
| value | string | Attribute value. |
Example
htmlEditor1.Content.SetAttributeValueOfAnElement("logo", "alt", "Company logo");GetOuterHtmlOfAnElement Method
Returns the outer HTML (including the element's own tag) of the element with the given id.
Syntax
string GetOuterHtmlOfAnElement(string elementId);Parameters
| Name | Type | Description |
|---|---|---|
| elementId | string | Element id. |
Returns
string -- outer HTML.
Example
string outerHtml = htmlEditor1.Content.GetOuterHtmlOfAnElement("intro");
Debug.WriteLine(outerHtml);GetInnerHtmlOfAnElement Method
Returns the inner HTML (the markup between the element's open and close tags) of the element with the given id.
Syntax
string GetInnerHtmlOfAnElement(string elementId);Parameters
| Name | Type | Description |
|---|---|---|
| elementId | string | Element id. |
Returns
string -- inner HTML.
Example
string innerHtml = htmlEditor1.Content.GetInnerHtmlOfAnElement("sidebar");UpdateInnerHtmlOfAnElement Method
Replaces the inner HTML of the element with the given id. Existing children are discarded.
Syntax
void UpdateInnerHtmlOfAnElement(string elementId, string newHtml);Parameters
| Name | Type | Description |
|---|---|---|
| elementId | string | Element id. |
| newHtml | string | Replacement inner markup. |
Example
htmlEditor1.Content.UpdateInnerHtmlOfAnElement("status", "<b>Updated</b>");GetHtmlElements Method
Returns a snapshot of every element in the document (or just the body, depending on the argument) as a System.Windows.Forms.HtmlElementCollection, which the host can enumerate to inspect or mutate elements.
Syntax
HtmlElementCollection GetHtmlElements(bool onlyBodyElements);Parameters
| Name | Type | Description |
|---|---|---|
| onlyBodyElements | bool | If true, only elements inside <body> are returned; otherwise all document elements. |
Returns
System.Windows.Forms.HtmlElementCollection -- the element collection.
Example
var elements = htmlEditor1.Content.GetHtmlElements(onlyBodyElements: true);
foreach (HtmlElement el in elements)
{
if (el.TagName == "IMG") Debug.WriteLine(el.GetAttribute("src"));
}GetBodyIHtmlElements Method
Returns the body elements as an mshtml.IHTMLElementCollection COM pointer. Use this when an MSHTML-style API surface is required (for example, when calling COM methods that expect MSHTML interfaces).
Syntax
IHTMLElementCollection GetBodyIHtmlElements();Returns
mshtml.IHTMLElementCollection -- the body element collection.
Example
IHTMLElementCollection coll = htmlEditor1.Content.GetBodyIHtmlElements();
foreach (IHTMLElement el in coll)
Debug.WriteLine(el.tagName);GetHtmlElementAt Method
Returns the topmost element under the supplied document coordinate as an mshtml.IHTMLElement. Useful for hit-testing custom commands or drag-and-drop targeting.
Syntax
IHTMLElement GetHtmlElementAt(Point caretPosition);Parameters
| Name | Type | Description |
|---|---|---|
| caretPosition | System.Drawing.Point | Document-space coordinate. |
Returns
mshtml.IHTMLElement -- the element at that point, or null.
Example
IHTMLElement hit = htmlEditor1.Content.GetHtmlElementAt(new Point(120, 80));
if (hit != null) Debug.WriteLine($"Hit: {hit.tagName}#{hit.id}");EmbedLocalImagesAsBase64 Method
Walks the document looking for <img> elements whose src resolves to a local file and rewrites each one into a Base64-encoded data: URI. After this call the document is self-contained -- safe to email or save as a single HTML file.
Syntax
void EmbedLocalImagesAsBase64();Example
htmlEditor1.Content.EmbedLocalImagesAsBase64();
string portable = htmlEditor1.Content.GetDocumentHtml();
File.WriteAllText(@"C:\temp\portable.html", portable);GetEmailMessageWithLocalImagesEmbedded Method
Builds and returns a System.Net.Mail.MailMessage whose HTML body is the current document with all local images converted to linked resources. Use this when sending the document as an email without writing your own MIME packaging.
Syntax
MailMessage GetEmailMessageWithLocalImagesEmbedded();Returns
System.Net.Mail.MailMessage -- the constructed message ready to hand to SmtpClient.Send.
Example
using (MailMessage msg = htmlEditor1.Content.GetEmailMessageWithLocalImagesEmbedded())
{
msg.From = new MailAddress("you@example.com");
msg.To.Add("customer@example.com");
msg.Subject = "Monthly report";
new SmtpClient("smtp.example.com").Send(msg);
}LoadBodyHtmlFromFile Method
Loads an HTML fragment from filePath using the given encoding and replaces the body content with it. The document head and DOCTYPE are preserved.
Syntax
void LoadBodyHtmlFromFile(string filePath, Encoding encoding);Parameters
| Name | Type | Description |
|---|---|---|
| filePath | string | Source file path. |
| encoding | System.Text.Encoding | File encoding (e.g. Encoding.UTF8). |
Example
htmlEditor1.Content.LoadBodyHtmlFromFile(@"C:\templates\body.html", Encoding.UTF8);LoadDocumentHtmlFromFile Method
Loads a complete HTML document from filePath using the given encoding and replaces the entire document.
Syntax
void LoadDocumentHtmlFromFile(string filePath, Encoding encoding);Parameters
| Name | Type | Description |
|---|---|---|
| filePath | string | Source file path. |
| encoding | System.Text.Encoding | File encoding. |
Example
htmlEditor1.Content.LoadDocumentHtmlFromFile(@"C:\templates\letter.html", Encoding.UTF8);SaveBodyHtmlToFile Method
Writes the body HTML to filePath. Existing files are overwritten.
Syntax
void SaveBodyHtmlToFile(string filePath);Parameters
| Name | Type | Description |
|---|---|---|
| filePath | string | Destination file path. |
Example
htmlEditor1.Content.SaveBodyHtmlToFile(@"C:\out\fragment.html");SaveDocumentHtmlToFile Method
Writes the complete HTML document (DOCTYPE, head, body) to filePath.
Syntax
void SaveDocumentHtmlToFile(string filePath);Parameters
| Name | Type | Description |
|---|---|---|
| filePath | string | Destination file path. |
Example
htmlEditor1.Content.SaveDocumentHtmlToFile(@"C:\out\full.html");SaveEditorContentAsXml Method
Serializes the document HTML as XML and writes it to the supplied file. Provided for host apps that store editor content as XML.
Syntax
void SaveEditorContentAsXml(string fileName);Parameters
| Name | Type | Description |
|---|---|---|
| fileName | string | Destination XML file path. |
Example
htmlEditor1.Content.SaveEditorContentAsXml(@"C:\out\snapshot.xml");OpenFile Method
Opens an HTML file from filePath and loads it into the editor. Encoding is detected automatically. Fires the editor's FileOpened event on success.
Syntax
void OpenFile(string filePath);Parameters
| Name | Type | Description |
|---|---|---|
| filePath | string | Path to an HTML file. |
Example
using (var dlg = new OpenFileDialog { Filter = "HTML files|*.html;*.htm" })
{
if (dlg.ShowDialog() == DialogResult.OK)
htmlEditor1.Content.OpenFile(dlg.FileName);
}ClearContent Method
Clears the document body. The document's head, DOCTYPE, and configured base URL are preserved.
Syntax
void ClearContent();Example
private void NewDocumentButton_Click(object sender, EventArgs e)
{
htmlEditor1.Content.ClearContent();
}UpdateBaseUrl Method
Updates the <base href> element of the document. Equivalent to assigning the WinFormHtmlEditor.BaseUrl property.
Syntax
void UpdateBaseUrl(string baseUrl);Parameters
| Name | Type | Description |
|---|---|---|
| baseUrl | string | The new base URL. |
Example
htmlEditor1.Content.UpdateBaseUrl("https://cdn.example.com/assets/");GetRightToLeft Method
Returns the document's right-to-left setting.
Syntax
RightToLeft GetRightToLeft();Returns
System.Windows.Forms.RightToLeft -- the RTL mode (Yes, No, or Inherit).
Example
RightToLeft rtl = htmlEditor1.Content.GetRightToLeft();
Debug.WriteLine($"Current RTL mode = {rtl}");SetRightToLeft Method
Sets the document's right-to-left direction. Use this for languages such as Arabic or Hebrew.
Syntax
void SetRightToLeft(RightToLeft rightToLeftValue);Parameters
| Name | Type | Description |
|---|---|---|
| rightToLeftValue | System.Windows.Forms.RightToLeft | RTL mode (Yes, No, or Inherit). |
Example
htmlEditor1.Content.SetRightToLeft(RightToLeft.Yes);ResetTableManipulator Method
Resets the table-authoring helper attached to the current document. Call this after restructuring tables programmatically so the next user interaction sees a fresh manipulator state.
Syntax
void ResetTableManipulator();Example
htmlEditor1.Content.SetBodyHtml(rebuiltHtml);
htmlEditor1.Content.ResetTableManipulator();Dispose Method (inherited from IDisposable)
Releases unmanaged resources held by the content service. The control disposes its services automatically when the control itself is disposed; host applications normally do not call this directly.
Syntax
void Dispose();Example
// The host control owns disposal -- only call this if you took ownership of the service.
htmlEditor1.Content.Dispose();TableAuthoringService Property
Gets or sets the table-authoring sub-service. The sub-service offers row/column/cell operations (insert before/after, delete, merge), zero-border guideline visibility, and selected-cell background color.
Syntax
ITableAuthoringService TableAuthoringService { get; set; }Property value
ITableAuthoringService -- the table-authoring service.
Remarks
Common members: InsertColumn(InsertPositions), DeleteColumn(), InsertRow(InsertPositions), DeleteRow(), MergeSelectedCells(), CanMergeCells(), ShowGuidelinesForTablesWithZeroBorder(bool), HideGuidelinesOfTablesWithZeroBorder(bool), IsTableBorderZero(IHTMLElement), SelectedCellBackgroundColor, EnableTableCellMerging, GetTableManipulator(), ResetTableManipulator().
Example
var tas = htmlEditor1.Content.TableAuthoringService;
tas.InsertRow(InsertPositions.Below);
if (tas.CanMergeCells()) tas.MergeSelectedCells();MailMerge Property
Gets the mail-merge placeholder insertion sub-service (Feature 2.5.5). The host application registers a list of PlaceholderField entries, and the editor lets the end user insert any of them as a placeholder span -- useful for building templates that are later filled per-record at send time.
Syntax
IMailMergeService MailMerge { get; }Property value
IMailMergeService -- the mail-merge service.
Remarks
Members: IList<PlaceholderField> PlaceholderFields { get; set; } -- fields registered for end-user insertion; void InsertPlaceholder(PlaceholderField field) -- inserts a placeholder span at the caret (ignored in source-edit mode); event EventHandler<PlaceholderInsertedEventArgs> PlaceholderInserted -- fires after a span is inserted with the field and emitted HTML.
Example
htmlEditor1.Content.MailMerge.PlaceholderFields = new List<PlaceholderField>
{
new PlaceholderField { Name = "FirstName", DisplayLabel = "First Name" },
new PlaceholderField { Name = "OrderTotal", DisplayLabel = "Order Total" }
};
htmlEditor1.Content.MailMerge.PlaceholderInserted += (s, e) =>
Debug.WriteLine($"Inserted {e.Field.Name}: {e.InsertedHtml}");Remarks
The member SetAttributeValueOfAnElementFromBODY appeared in older releases but has been removed; use SetAttributeValueOfAnElement for both head and body elements. Methods that depend on a live MSHTML document require the editor to be in WYSIWYG design mode -- calls made in source-edit mode are either ignored or return last-loaded data. All calls must be made on the UI thread.