How do I detect when the content of a WebBrowser control has changed (in design mode)?

生来就可爱ヽ(ⅴ<●) 提交于 2020-06-25 19:04:28

问题


I'm using a WebBrowser control in design mode.

webBrowser1.DocumentText = "<html><body></body></html>";
doc = webBrowser1.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";

I have a save button that I would like to enable or disable depending on whether the contents of the control have changed.

I also need to know when the contents of the control have changed as I need to stop the user from navigating away from the control without accepting a confirmation message box stating that their changes will be lost.

I can't find any events that would let me know that the contents have changed.


回答1:


There is no such event since DocumentText is a simple string. I would create a string variable storing the last saved text and check it at each KeyDown / MouseDown / Navigating event.

string lastSaved;

private void Form_Load(object sender, System.EventArgs e)
{
   // Load the form then save WebBrowser text
   this.lastSaved = this.webBrowser1.DocumentText;
}

private void webBrowser1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Check if it changed
    if (this.lastSaved != this.webBrowser1.DocumentText)
    {
        // TODO: changed, enable save button
        this.lastSaved = this.webBrowser1.DocumentText;
    }
}

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    // Check if it changed
    if (this.lastSaved != this.webBrowser1.DocumentText)
    {
        // TODO: ask user if he wants to save
        // You can set e.Cancel = true to cancel loading the next page
    }
}



回答2:


QI the document for IMarkupContainer2, then call IMarkupContainer2::RegisterForDirtyRange with your own implementation of IHTMLChangeSink. Your IHTMLChangeSink::Notify implementation will be called when a change is made.

Note do this after you set the design mode. the document gets reloaded and event hook get lost if you toogle the design mode.




回答3:


another solution, if you implement IDocHostUIHandler, you can use its method UpdateUI



来源:https://stackoverflow.com/questions/11135743/how-do-i-detect-when-the-content-of-a-webbrowser-control-has-changed-in-design

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!