views:

302

answers:

2

In my IE extension I am trying to get the screen co-ordinates of an element in C++/MSHTML. From my IHTMLDocument2, I do the following:

IHTMLDocument2:: pDoc->get_all(&pElemColl);
IHTMLElementCollection::pElemColl->item(varID, varIdx, &pElemDisp);

where

_variant_t varID = ("myID", VT_BSTR);
//myID is the tag name of the element I'm trying to get. In this case it it an id of a input field
//I've also tried getting bounded area of div's and textarea
_variant_t varIdx = (0, VT_I4);

then

IDispatch::pElemDisp->QueryInterface(IID_IHTMLElement, (void**) &pElem);
IHTMLElement::pElem->QueryInterface(IID_IHTMLElement2, (void**) &pElem2);
IHTMLElement2::pElem2->getBoundingClientRect(&childRect);//Defined as IHTMLRect *childRect;

For every query that I've done, I've checked the return value insuring that its S_OK. The call to getBoundingClientRect is successful as well, i.e., it returns S_OK, but all the components of childRect (i.e, top, bottom, left, right) return 0. I don't what may have gone wrong. Any ideas?

Edit: I converted the co-ordinates I get from getBoundingClientRect to Screen co-ordinates. So the co-ordinate I receive for the top-left corresponds to the top left corner of my IE window, and the coordinates for the bottom right is the same as the top left. This happens for any DOM element in the page. For example in the stackoverflow's "Ask Question" page, if I try to get bounding coordinates for the textbox id : wmd-input (the big box where you describe the question), I get the same result as I specified above.

A: 

Update: If I get the active element in the page by calling IHTMLDocument2::get_activeElement and then call get_BoundingClientRect, then the co-ordinates I receive are correct. SO the question now is, how would I get the co-ordinate of a non-active element (i.e, get the co-ordinates of an element by its id) in a page - because as mentioned in my earlier post, the code I try only returns me the co-ordinates of the top-left corner of the IE window. Here is what I'm doing now:

IHTMLDocument2:: pDoc->get_activeElement(&pElement);
IHTMLElement:: pElement->QueryInterface(IID_IHTMLElement2, (void**) &pElem2);
IHTMLElement2::pElem2->getBoundingClientRect(&childRect);//Defined as IHTMLRect *childRect;
 //The co-ordinates that get's returned is absolutely correct
GotAmye
A: 

Turns out, the best way to get an element by its id is to use IHTMLDocument3::getElementById ALL is well!

GotAmye