MSHTML Hosting – More Editing

Previously I talked about exposing the HTML editor hiding inside the WebBrowser control. I also talked about IOleCommandTarget and how you can control formatting and layout features of the editor. It won’t take long before you discover that the IOleCommandTarget command ID’s are somewhat limited. At some point, you will need to insert specialized text or HTML at the current cursor location or replacing the current selection. Luckily for us, there is an easy way to do it: IHTMLTxtRange.

I talked about IHTMLTxtRange in a previous post. It is useful for finding text or getting the text of the current selection. It can also do the reverse: It can insert text or HTML at the current cursor location or selection using the pasteHTML method. Here’s a simple example:


IHTMLDocument2* pDoc = ...;

IHTMLSelectionObject* pSelection = 0;
HRESULT hr = pDoc->get_selection(&pSelection);
if (SUCCEEDED(hr)) {
   IDispatch* pDispRange = 0;
   hr = pSelection->createRange(&pDispRange);
   if (SUCCEEDED(hr)) {
      IHTMLTxtRange* pTextRange = 0;
      hr = pDispRange->QueryInterface(IID_IHTMLTxtRange, (void**)&pTextRange);
      if (SUCCEEDED(hr)) {
         CComBSTR sText = L"This is <b>better</b> text";
         pTextRange->get_pasteHTML(sText);
         pTextRange->Release();
      }
      pDispRange->Release();
   }
   pSelection->Release();
}

pDoc->Release();

In the above example, the selection may have selected text or it may just be a cursor location. The HTML overwrites any selected text. Otherwise, it’s inserted at the cursor location.

Overall, IHTMLTxtRange is a very useful interface. I have used it for implementing spell check, find/replace and inserting complex HTML. Just to be clear, IHTMLTxtRange works when design mode is off or on. The WebBrowser control does not need to be in edit mode to call pasteHTML.