public IWebBrowser2 GetBrowserFromWindow(IHTMLWindow2 win)
{
if(win == null)
{
throw new ArgumentNullException("win");
}
IWebBrowser2 result = null;
//if the document is the top level document, we don't have to look for it
if(win.document == this.CurrentDocument)
{
result = this.IWebBrowser2; //internal reference to the top-level IWebBrowser2
}
else
{
//get the OLE container from the window's parent
IOleContainer oc = win.parent.document as IOleContainer; //OC ALLOC
//get the OLE enumerator for the embedded objects
int hr = 0;
IEnumUnknown eu;
hr = oc.EnumObjects(tagOLECONTF.OLECONTF_EMBEDDINGS, out eu); //EU ALLOC
Marshal.ReleaseComObject(oc); //OC FREE
Marshal.ThrowExceptionForHR(hr);
Guid IID_IWebBrowser2 = typeof(SHDocVw.IWebBrowser2).GUID;
object pUnk = null;
int fetched = 0;
const int MAX_FETCH_COUNT = 1;
//get the first embedded object
hr = eu.Next(MAX_FETCH_COUNT, out pUnk, out fetched); //PUNK ALLOC
Marshal.ThrowExceptionForHR(hr);
//while sucessfully get a new embedding, continue
for(int i = 0; HRESULTS.S_OK == hr; i++)
{
//QI pUnk for the IWebBrowser2 interface
SHDocVw.IWebBrowser2 brow = pUnk as SHDocVw.IWebBrowser2;
if(brow != null)
{
//if the document for this browser matches the one passed in, we found it
if(brow.Document == win.document)
{
result = brow;
break;
}
else
{
Marshal.ReleaseComObject(brow); //PUNK FREE
}
} //if(brow != null)
//get the next ebmedded object
hr = eu.Next(MAX_FETCH_COUNT, out pUnk, out fetched); //PUNK ALLOC
Marshal.ThrowExceptionForHR(hr);
} //for(int i = 0; HRESULTS.S_OK == hr; i++)
Marshal.ReleaseComObject(eu); //EU FREE
}
return result;
}