您不必执行任何手动编组;托管运行时代表您处理任何跨单元 COM 对象封送处理。
这是一个例子;此示例托管 BHO 一直等到 DocumentComplete 事件触发并启动 ThreadPool 后台线程,该线程等待一秒钟,然后将页面标题更改为“Hello,StackOverflow!” 并添加一个带有特殊消息的新文本节点:
private void OnDocumentComplete(object frame, ref object urlObj)
{
System.Threading.ThreadPool.QueueUserWorkItem((o) =>
{
System.Threading.Thread.Sleep(1000);
HTMLDocument document = (HTMLDocument)this.browser.Document;
document.title = "Hello, StackOverflow!";
IHTMLDOMNode greetings = document.createTextNode("Hi there!");
IHTMLDOMNode body = document.body as IHTMLDOMNode;
body.insertBefore(greetings, body.firstChild);
}, this.browser);
}
#region IObjectWithSite Members
int IObjectWithSite.SetSite(object site)
{
if (site != null)
{
this.browser = (WebBrowser)site;
this.browser.DocumentComplete +=
new DWebBrowserEvents2_DocumentCompleteEventHandler(
this.OnDocumentComplete);
}
else
{
if (this.browser != null)
{
this.browser.DocumentComplete -=
new DWebBrowserEvents2_DocumentCompleteEventHandler(
this.OnDocumentComplete);
this.browser = null;
}
}
return 0;
}
int IObjectWithSite.GetSite(ref Guid guid, out IntPtr ppvSite)
{
IntPtr punk = Marshal.GetIUnknownForObject(this.browser);
int hr = Marshal.QueryInterface(punk, ref guid, out ppvSite);
Marshal.Release(punk);
return hr;
}
#endregion