改變HTML中的光標問題
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();? // http://www.wzszf.com/
}
其中,pElem 是指定要跳到的元素(我的情況下,它是一個 <div> </div>,這段代碼可以使光標移到那個元素上,而且那個空位也被選上。但是我衹想要光標移動,不想要文字被選取,我嘗試去掉 txtRange->select() 這一段,但那樣光標又不移動
我是利用 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 是我新插入的元素
實在想不到好辦法,最後衹好用下面這個笨方法
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();?
}
總結
以上是生活随笔為你收集整理的改變HTML中的光標問題的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [OS复习]虚拟存储管理技术 1
- 下一篇: 按摩椅浏览器测试浏览器可视窗口大小