MSHTML Hosting – More Tricks

Here are a couple miscellaneous tips for using the WebBrowser while in design (edit) mode.

Setting Focus In Design Mode

With the WebBrowser control in design mode, there are times that focus (and the blinking cursor) are not set correctly. For example, with focus in the editor, ALT+TAB away from your application, and then back again. Focus may not be set back into the editor. Here is a simple way to fix it. Put this code in an event or message handler that gets called when your application is re-activated:


IHTMLDocument2* pHTMLDoc2 = ...;
IHTMLWindow2* pWindow = 0;
pHtmlDoc2->get_parentWindow(&spWindow);
if (pWindow) {
  pWindow->focus();
  pWindow->Release();
}

Unselecting Current Selection

IHTMLTxtRange has a method to easily select a range of text, but there is no simple method to unselect an existing text selection. Here is a simple way to do it:


IHTMLDocument2* pHTMLDoc2 = ...;
IHTMLSelectionObject* pSelection = 0;
pHTMLDoc2->get_selection(&pSelection);
if (pSelection) {
  IDispatch* pDispRange = 0;
  pSelection->createRange(&pDispRange);

  IHTMLTxtRange* pTxtRange = 0;
  pDispRange->QueryInterface(IID_IHTMLTxtRange, (void**)&pTxtRange);
  if (pTxtRange) {
    VARIANT_BOOL bSuccess;
    pTxtRange->execCommand(CComBSTR(L"Unselect"), VARIANT_FALSE, CComVariant(), &bSuccess);
    pTxtRange->Release();
  }
  pDispRange->Release();
  pSelection->Release();
}