监控 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


}


返回导读目录,阅读更多随笔



分割线,以下为博客签名:

软件臭虫情未了
  • 编码一分钟
  • 测试十年功


随笔如有错误或不恰当之处、为希望不误导他人,望大侠们给予批评指正。

原文地址:https://www.cnblogs.com/08shiyan/p/1957995.html