我在網上找到這一段代碼,用來改變當前光標位置HRESULT hr;
CComPtr<IHTMLTxtRange> txtRange;
CComPtr<IHTMLSelectionObject> pSelection;
spDoc->get_selection(&pSelection);
if (pSelection)
{
  CComPtr<IDispatch> pDispRange;
  pSelection->createRange(&pDispRange);
  if (pDispRange)
  {
    hr = pDispRange->QueryInterface(IID_IHTMLTxtRange, (void**)&txtRange);
    if ( SUCCEEDED(hr) && txtRange )
    { 
      txtRange->collapse(VARIANT_TRUE);
      if (pElem)
      {
        if (SUCCEEDED(txtRange->moveToElementText(pElem)))
        { 
          txtRange->select();
          txtRange->scrollIntoView();
        }
      }
      txtRange.Release();
    }
    pDispRange.Release();
  }
  pSelection.Release();
}其中,pElem 是指定要跳到的元素(我的情況下,它是一個 <div>&nbsp;</div>,這段代碼可以使光標移到那個元素上,而且那個空位也被選上。但是我衹想要光標移動,不想要文字被選取,我嘗試去掉 txtRange->select() 這一段,但那樣光標又不移動

解决方案 »

  1.   

    我是利用 IHTMLDocument2.createElement 來生成新的元素,然後用 IHTMLDOMNode.appendChild插入到指定位置上,插入元素沒有問題。但光標就是移不過去。我後來改用下面的代碼,但還是沒效HRESULT hr;
    CComPtr<IMarkupServices> pMS;
    CComPtr<IMarkupContainer> pMarkup;
    CComPtr<IMarkupPointer> pPtr;
    CComPtr<IDisplayPointer> dpPtr;
    CComPtr<IDisplayServices> pDispServices;
    CComPtr<IHTMLCaret> spCaret; hr = spDoc->QueryInterface(IID_IMarkupContainer, (void **)&pMarkup);
    if (hr==S_OK)

      hr = spDoc->QueryInterface(IID_IMarkupServices, (void **)&pMS);
      if (hr==S_OK) 
      { 
        pMS->CreateMarkupPointer(&pPtr);
        hr = spDoc->QueryInterface(IID_IDisplayServices, (void **)&pDispServices);
        if (hr==S_OK)
        { 
          pDispServices->CreateDisplayPointer(&dpPtr);
          pDispServices->GetCaret(&spCaret);
          pMS->CreateMarkupPointer(&pPtr);
          pPtr->MoveAdjacentToElement( pElem, ELEM_ADJ_AfterEnd);
          dpPtr->MoveToMarkupPointer(pPtr, dpPtr);
          spCaret->MoveCaretToPointer(dpPtr, TRUE,  CARET_DIRECTION_SAME);
        }
      }
    }上面的代碼中,pElem 是我新插入的元素
      

  2.   

    實在想不到好辦法,最後衹好用下面這個笨方法HRESULT hr; 
    CComPtr <IHTMLTxtRange> txtRange; 
    CComPtr <IHTMLSelectionObject> pSelection; 
    spDoc->get_selection(&pSelection); 
    if (pSelection) 

      CComPtr <IDispatch> pDispRange; 
      pSelection->createRange(&pDispRange); 
      if (pDispRange) 
      { 
        hr = pDispRange->QueryInterface(IID_IHTMLTxtRange, (void**)&txtRange); 
        if ( SUCCEEDED(hr) && txtRange ) 
        { 
          txtRange->collapse(VARIANT_TRUE); 
          if (pElem) 
          { 
            if (SUCCEEDED(txtRange->moveToElementText(pElem))) 
            { long n;
              txtRange->move(L"character", 1, &n);    // 向前進一步
              txtRange->move(L"character", -1, &n);   // 然後退回去,這樣就移動了光標 
              txtRange->select(); 
              txtRange->scrollIntoView(); 
            } 
          } 
          txtRange.Release(); 
        } 
        pDispRange.Release(); 
      } 
      pSelection.Release();