gpt4 book ai didi

c# - DocumentComplete 在页面完全加载之前触发

转载 作者:行者123 更新时间:2023-11-30 22:33:18 25 4
gpt4 key购买 nike

为什么 WebBrowser COM 对象的 DocumentComplete 事件会在页面加载前触发?我认为只有当页面在浏览器窗口中完全呈现时才会触发此事件。

这是我的 BHO 实现:

[ComVisible(true),
Guid("5a954357-44bd-4660-9570-17bb1b71eeaa"),
ClassInterface(ClassInterfaceType.None)]
public class BHO : IObjectWithSite
{
private WebBrowser browser;
private DateTime startTime;
private DateTime endTime;
private object _pUnkSite;

public void OnDocumentComplete(object pDisp, ref object URL)
{
if (!ReferenceEquals(pDisp, _pUnkSite))
{
return;
}

using (StreamWriter sw = File.AppendText("log_path"))
{
endTime = DateTime.Now;
TimeSpan ts = endTime.Subtract(startTime);
sw.WriteLine("completed in {0}.{1}", ts.Seconds, ts.Milliseconds);
}

}

public void OnBeforeNavigate2(object pDisp, ref object URL, ref object Flags, ref object TargetFrameName, ref object PostData, ref object Headers, ref bool Cancel)
{
if (!ReferenceEquals(pDisp, _pUnkSite))
{
return;
}
startTime = DateTime.Now;
}

public int SetSite(object site)
{
if (site != null)
{
_pUnkSite = site;
browser = (WebBrowser)site;
browser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
browser.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(this.OnBeforeNavigate2);
}
else
{
browser.DocumentComplete -= new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
browser.BeforeNavigate2 -= new DWebBrowserEvents2_BeforeNavigate2EventHandler(this.OnBeforeNavigate2);
browser = null;

}
return 0;
}

public int GetSite(ref Guid guid, out IntPtr ppvSite)
{
IntPtr punk = Marshal.GetIUnknownForObject(browser);
int hr = Marshal.QueryInterface(punk, ref guid, out ppvSite);
Marshal.Release(punk);

return hr;
}
}

最佳答案

因为一个页面上还有其他文档。例如,iframe 或图像将触发 DocumentComplete 事件。您需要做的是确保引发 DocumentComplete 的对象是实际页面。例如:

private void _webBrowser2Events_DocumentComplete(object pdisp, ref object url)
{
if (!ReferenceEquals(pdisp, _pUnkSite))
{
//Exit, because the DocumentComplete is not the document complete for the page.
return;
}
//Do your normal stuff here
}

其中 _pUnkSite 是从 SetSite 传入的站点.

关于c# - DocumentComplete 在页面完全加载之前触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8359379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com