监控 WebBrowser 控件内容的改变

今天的收获只有一项,那就是这个啦。。。
呵呵, 主要的就是用到mshtml.IHTMLChangeSink 中的 Notify方法触发自定义的事件,具体的代码我也不懂,嘿嘿 这些都是从 东西市 Copy 来的,乱的成粥了。

几点核心代码:


public class Monitor : mshtml.IHTMLChangeSink
{
// for monitor htmleditor textchanged
private Guid IMarkupContainer2GUID = typeof(mshtml.IMarkupContainer2).GUID;
   
private uint cookie = 0;

private mshtml.IMarkupContainer2 markupContainer;

  
private WebBrowser webBrowser;

   
// Event
public event Action HtmlEditorEvent;


 
public Monitor(WebBrowser webControl)

   {
      
this.webBrowser= webControl;
}


#region For HtmlEditor TextChanged

// always monitor
private mshtml.IMarkupContainer2 GetMarkupContainer()
{
object oDocument = this.webBrowser.Document.DomDocument;

IntPtr pDocument
= Marshal.GetIUnknownForObject(oDocument);

IntPtr pMarkupContainer
= IntPtr.Zero;

// pMarkupContainer is different after a call to Navigate or designMode

Marshal.QueryInterface(pDocument,
ref IMarkupContainer2GUID, out pMarkupContainer);

//object oMarkupContainer = Marshal.GetObjectForIUnknown(pMarkupContainer); // This does not work

object oMarkupContainer = Marshal.GetUniqueObjectForIUnknown(pMarkupContainer);

Marshal.Release(pDocument);

Marshal.Release(pMarkupContainer);

return (mshtml.IMarkupContainer2)oMarkupContainer;

}


// only one monitor
private mshtml.IMarkupContainer2 GetMarkupContainer2()
{
return (mshtml.IMarkupContainer2)this.webBrowser.Document.DomDocument;
}


public void MonitorTextChangedAlways()
{
this.markupContainer = GetMarkupContainer();

this.markupContainer.RegisterForDirtyRange((mshtml.IHTMLChangeSink)this, out this.cookie);
}


public void StopMonitorTextChanged()
{
if (this.markupContainer != null)
{
this.markupContainer.UnRegisterForDirtyRange(this.cookie);
}
}

#endregion


#region Implement Interface

public void Notify()
{
//触发改变事件外界去接受
if (this.HtmlEditorEvent != null)
{
this.HtmlEditorEvent();
}
}

#endregion


}
posted @ 2011-02-18 16:25  把爱延续  阅读(...)  评论(...编辑  收藏