简体   繁体   中英

How to detect document changes when using the MSHTML WebBrowser in edit mode using C# in Windows Forms?

I'm using the .NET WebBrowser control in a WinForms application to implement a very basic e-mail template editor.

I've set it in edit mode by this code:

wbEmailText.Navigate( "about:blank" );
( (HTMLDocument)wbEmailText.Document.DomDocument ).designMode = "On";

So the user can modify the WebBrowser content. Now I need to detect when the user modifies the content 'cause I have to validate it. I've tried to use some WebBrowser's events like DocumentCompleted, Navigated, etc. but no-one of these worked. Could someone give me advice, please? Thanks in advance!

I did have some working, really world code but that project is about 5 years old and I've since left the company. I've trawled my back-ups but can't find it so I am trying to work from memory and give you some pointers.

There are lots of events you can catch and then hook into to find out whether a change has been made. A list of the events can be found here: http://msdn.microsoft.com/en-us/library/ms535862(v=vs.85).aspx

What we did was catch key events (they're typing) and click events (they've moved focus or dragged / dropped etc) and handled that.

Some example code, note a few bits are pseudo code because I couldn't remember off the top of my head the actual code.

// Pseudo code
private string _content = string.empty;

private void frmMain_Load(object sender, EventArgs e)
{
    // This tells the browser that any javascript requests that call "window.external..." to use this form, useful if you want to hook up events so the browser can notify us of things via JavaScript
    webBrowser1.ObjectForScripting = this;
    webBrowser1.Url = new Uri("yourUrlHere");
}

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    // Store original content
    _content = webBrowser1.Content; // Pseudo code
    webBrowser1.Document.Click += new HtmlElementEventHandler(Document_Click);
    webBrowser1.Document.PreviewKeyDown +=new PreviewKeyDownEventHandler(Document_PreviewKeyDown);
}

protected void Document_Click(object sender, EventArgs e)
{
    DocumentChanged();
}

protected void Document_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    DocumentChanged();
}

private void DocumentChanged()
{
    // Compare old content with new content
    if (_content == webBrowser1.Content)    // Pseudo code
    {
        // No changes made...
        return;
    }

    // Add code to handle the change
    // ...

    // Store current content so can compare on next event etc
    _content = webBrowser1.Content; // Pseudo code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM