Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 366
crdx Avatar asked Jun 21 '12 09:06

crdx


2 Answers

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
    }
}
like image 155
nXu Avatar answered Nov 15 '22 06:11

nXu


QueryInterface() 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 toggle the design mode.

like image 29
Sheng Jiang 蒋晟 Avatar answered Nov 15 '22 06:11

Sheng Jiang 蒋晟