如何检测 WebBrowser 控件的内容何时发生更改(在设计模式下)?

crd*_*rdx 5 c# webbrowser-control

WebBrowser在设计模式下使用控件。

webBrowser1.DocumentText = "<html><body></body></html>";
doc = webBrowser1.Document.DomDocument as IHTMLDocument2;
doc.designMode = "On";
Run Code Online (Sandbox Code Playgroud)

我有一个保存按钮,我想根据控件的内容是否已更改启用或禁用该按钮。

我还需要知道控件的内容何时发生更改,因为我需要阻止用户离开控件而不接受说明其更改将丢失的确认消息框。

我找不到任何让我知道内容已更改的事件。

nXu*_*nXu 3

由于 DocumentText 是一个简单的字符串,因此不存在此类事件。我将创建一个字符串变量来存储最后保存的文本,并在每个 KeyDown / MouseDown / Navigating 事件中检查它。

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
    }
}
Run Code Online (Sandbox Code Playgroud)